Reputation: 393
I would like to include only the contents of certain block of another template. Is it possible to access only the contents of a block and not the whole file?
As far as I can see it, embed
and include
always include and output the whole file. And use
imports all blocks and apparently (?) the destination file needs to be hard-coded and cannot be an expression or a variable passed to the template. Is that correct?
Upvotes: 12
Views: 22233
Reputation: 4526
Using partials
will be a better solution for it.
I don't think that it is possible to access a block
of another template
in twig
.
Every time that I need to reuse parts of a template
, I create a partial
for them.
Partials could follow a different path, like _partials/Header.twig.html
and you can include this in template with variables {% include '_partials/Header.twig.html' with {bar: 'foo'}%}
Upvotes: 4
Reputation: 4468
Use a macro https://twig.symfony.com/doc/2.x/tags/macro.html
Render a block template (used by web profiler): https://twig.symfony.com/doc/2.x/functions/block.html
{{ block("title", "common_blocks.twig") }}
The Symfony WebProfiler it is a great example:
vendor/symfony/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig
Each profiler view template has 3 blocks:
Then it renders each block depending on when it is required.
Toolbar example: vendor/symfony/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.html.twig
<!-- START of Symfony Web Debug Toolbar -->
<div id="sfMiniToolbar-{{ token }}" class="sf-minitoolbar" data-no-turbolink>
<a href="#" title="Show Symfony toolbar" tabindex="-1" id="sfToolbarMiniToggler-{{ token }}" accesskey="D">
{{ include('@WebProfiler/Icon/symfony.svg') }}
</a>
</div>
<div id="sfToolbarClearer-{{ token }}" class="sf-toolbar-clearer"></div>
<div id="sfToolbarMainContent-{{ token }}" class="sf-toolbarreset clear-fix" data-no-turbolink>
{% for name, template in templates %}
{% if block('toolbar', template) is defined %}
{% with {
collector: profile.getcollector(name),
profiler_url: profiler_url,
token: profile.token,
name: name,
profiler_markup_version: profiler_markup_version,
csp_script_nonce: csp_script_nonce,
csp_style_nonce: csp_style_nonce
} %}
{{ block('toolbar', template) }}
{% endwith %}
{% endif %}
{% endfor %}
<a class="hide-button" id="sfToolbarHideButton-{{ token }}" title="Close Toolbar" tabindex="-1" accesskey="D">
{{ include('@WebProfiler/Icon/close.svg') }}
</a>
</div>
<!-- END of Symfony Web Debug Toolbar -->
Upvotes: 19