twig继承和symfony2控制器变量 [英] twig inheritance and symfony2 controller variables

查看:252
本文介绍了twig继承和symfony2控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying my first project using symfony2 + twig. I created basic twig template with defined blocks. It basically looks like this

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

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

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

I want footer to be same for all pages. Footer is loaded from DB and its set in controller. I wanted inherit from template described above to other pages but I have to always set footer in controller otherwise variable is not defined.

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

My questions is if exists any 'nice' way how to set footer variable for multiple templates inherited from parent template?

推荐答案

解决方案:嵌入式控制器

The solution : 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

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)
        );
    }
}

查看

View

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

布局

Layout

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

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

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

这篇关于twig继承和symfony2控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆