简体   繁体   English

Symfony2 / Twig - 如何将模板文件内容设置为变量?

[英]Symfony2/Twig - how to set template file contents as variable?

In Symfony 2.8 I've got SharedBundle , where I keep views and other things I share between other bundles, including the whole layout that should be extended by other bundles' views. 在Symfony 2.8中,我有了SharedBundle ,在那里我保存了其他bundle之间共享的视图和其他内容,包括应该由其他bundle视图扩展的整个布局。
That shared layout has some typical blocks, from which sidebar block should be different for different bundles. 该共享布局具有一些典型的块,对于不同的束, sidebar块应该是不同的。

Currently I did an ugly workaround: 目前我做了一个丑陋的解决方法:

In SharedBundle sidebar container: SharedBundle侧边栏容器中:

{% if sidebarcontent is defined %}
    {{ sidebarcontent|raw }}
{% else %}
    SIDEBAR NOT FOUND
{% endif %}

And in other bundles (here: BundleA ) in every view that extends the shared main view: 在扩展共享主视图的每个视图中的其他bundle(此处为: BundleA )中:

{% extends 'SharedBundle:layout.html.twig' %}
{% block sidebar %}
    {% include 'BundleA:_partials:sidebar.html.twig' %}
{% endblock %}
{% set sidebarcontent =  block('sidebar') %}

But that doesn't look good, I think. 但我觉得这看起来不太好看。 Is there a better way? 有没有更好的办法?

I think this is a valid approach. 我认为这是一种有效的方法。 The only simplification I can think of is not using the variable sidebarcontent . 我能想到的唯一简化就是不使用变量sidebarcontent

You can use block('sidebar') inside the if statement: 你可以在if语句中使用block('sidebar')

{% if block('sidebar')|length > 0 %}
    {{ sidebarcontent|raw }}
{% else %}
    SIDEBAR NOT FOUND
{% endif %}

Make sure the block exists before checking it's content, so initialise it with an empty string: 在检查内容之前确保该块存在,因此使用空字符串初始化它:

{% block sidebar %}{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM