【问题标题】:Twig / Symfony2 Dynamic TemplateTwig / Symfony2 动态模板
【发布时间】:2013-04-08 08:10:05
【问题描述】:

我想做这种事情,这样如果模板不存在,它只会呈现内容。下面的代码不起作用,因为你不能这样编码。

{% if app.request.attributes.get('twig_parent_template') != "" %}
    {% extends app.request.attributes.get('twig_parent_template') %}
    {% block title "The Title Here" %}
{% endif %}

{% block content %}
Content here
{% endblock %}

我能以某种方式做这种事情吗?

【问题讨论】:

    标签: symfony twig


    【解决方案1】:

    Twig extends 对此主题有很好的文档。

    由于您需要指定要扩展的模板,所以我的想法是创建一个默认模板。

    @Bundle/Resources/views/yourview.html.twig

    {% set extender = app.request.attributes.get('twig_parent_template') ? : 'Bundle::default.html.twig' %}
    {% extends extender %}
    
    {% block title "Your title" %}
    {% block content %}
        Your content
    {% endblock %}
    

    @Bundle/Resources/views/default.html.twig

    {% block content %}{% endblock %}
    

    @Bundle/Resources/views/parent.html.twig

    {% block title %}{% endblock %}
    {% block content %}{% endblock %}
    

    这样做,如果设置了app.request.attributes.get('twig_parent_template'),它将呈现在其值中给定的模板。
    否则,它将呈现仅包含 content 块的 default.html.twig

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      相关资源
      最近更新 更多