我想只包含另一个模板中某个块的内容。是否有可能访问块内的内容而不是整个文件?
据我所见,embed
和include
始终包含和输出整个文件。而use
导入所有块,显然(?)目标文件需要硬编码,不能是传递给模板的表达式或变量。这正确吗?
使用宏 https://twig.symfony.com/doc/2.x/tags/macro.html
渲染块模板(由 Web 分析器使用):https://twig.symfony.com/doc/2.x/functions/block.html
{{ block("title", "common_blocks.twig") }}
Symfony WebProfiler是一个很好的例子:
vendor/symfony/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig
每个分析器视图模板都有三个块:
然后根据需要渲染每个块。
工具栏示例: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 -->
partials
会是更好的解决方案。twig
中无法访问另一个template
的block
。template
的部分时,我都会为它们创建一个partial
。
Partials
可以遵循不同的路径,如_partials/Header.twig.html
,并且您可以使用变量在模板中包含它们,如{% include '_partials/Header.twig.html' with {bar: 'foo'}%}
。