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

查看:19
本文介绍了树枝继承和 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 %}

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

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?

推荐答案

解决方案:嵌入控制器

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

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:

控制器

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

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 #}

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

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

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

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