gpt4 book ai didi

symfony - twig 继承和 symfony2 Controller 变量

转载 作者:行者123 更新时间:2023-12-01 09:54:18 26 4
gpt4 key购买 nike

我正在使用 symfony2 + twig 尝试我的第一个项目。我创建了带有定义 block 的基本 Twig 模板。基本上是这样的

{% block content %}
some content...
{% endblock %}

{% block footer %}
{{ footer.content}}
{% endblock %}

我希望所有页面的页脚都相同。页脚从数据库加载,并在 Controller 中设置。我想从上述模板继承到其他页面,但我必须始终在 Controller 中设置页脚,否则 undefined variable 。

我的问题是是否存在如何为从父模板继承的多个模板设置页脚变量的“好”方法?

最佳答案

解决方案:Embedding Controllers

In some cases, you need to do more than include a simple template. Suppose you have a sidebar in your layout that contains the three most recent articles. Retrieving the three articles may include querying the database or performing other heavy logic that can't be done from within a template.

The solution is to simply embed the result of an entire controller from your template. First, create a controller that renders a certain number of recent articles:

Controller

// src/AppBundle/Controller/ArticleController.php
namespace AppBundle\Controller;
// ...

class ArticleController extends Controller
{
public function recentArticlesAction($max = 3)
{
// make a database call or other logic
// to get the "$max" most recent articles
$articles = ...;

return $this->render(
'article/recent_list.html.twig',
array('articles' => $articles)
);
}
}

查看

{# app/Resources/views/article/recent_list.html.twig #}
{% for article in articles %}
<a href="/article/{{ article.slug }}">
{{ article.title }}
</a>
{% endfor %}

布局

{# app/Resources/views/base.html.twig #}

{# ... #}
<div id="sidebar">
{{ render(controller(
'AppBundle:Article:recentArticles',
{ 'max': 3 }
)) }}
</div>

关于symfony - twig 继承和 symfony2 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com