twig继承和symfony2控制器变量

mar*_*ech 3 inheritance symfony twig

我正在使用symfony2 + twig尝试我的第一个项目.我创建了具有已定义块的基本树枝模板.它基本上看起来像这样

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

{% block footer %}
  {{ footer.content}}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

我希望所有页面的页脚都相同.页脚从DB加载并在控制器中设置.我希望从上面描述的模板继承到其他页面,但我必须始终在控制器中设置页脚,否则未定义变量.

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

小智 7

解决方案:嵌入控制器

在某些情况下,您需要做的不仅仅是包含一个简单的模板.假设您的布局中有一个侧栏,其中包含三篇最新文章.检索这三篇文章可能包括查询数据库或执行无法在模板中完成的其他繁重逻辑.

解决方案是简单地从模板中嵌入整个控制器的结果.首先,创建一个呈现一定数量的最近文章的控制器:

调节器

// 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)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

视图

{# app/Resources/views/article/recent_list.html.twig #}
{% for article in articles %}
    <a href="/article/{{ article.slug }}">
        {{ article.title }}
    </a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

布局

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

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