简体   繁体   中英

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.
That shared layout has some typical blocks, from which sidebar block should be different for different bundles.

Currently I did an ugly workaround:

In SharedBundle sidebar container:

{% 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:

{% 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 .

You can use block('sidebar') inside the if statement:

{% 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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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