Twig:包含另一个模板的块

11

我想只包含另一个模板中某个块的内容。是否有可能访问块内的内容而不是整个文件?

据我所见,embedinclude始终包含和输出整个文件。而use导入所有块,显然(?)目标文件需要硬编码,不能是传递给模板的表达式或变量。这正确吗?

2个回答

18

使用宏 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 - 使用块和模板的有趣用法

Symfony WebProfiler是一个很好的例子:

vendor/symfony/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig

每个分析器视图模板都有三个块:

  1. 菜单
  2. 面板
  3. 工具栏

然后根据需要渲染每个块。

工具栏示例: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 -->

渲染一个看起来不错的块。奇怪我之前没找到它。如果该块在另一个文件中,那么文件路径是否可以作为变量传递,还是需要直接硬编码为字符串? - tungsten
1
你可以在示例中看到文件如何作为变量和块名称传递。 - albert

4
使用partials会是更好的解决方案。
我认为在twig中无法访问另一个templateblock
每次需要重用template的部分时,我都会为它们创建一个partialPartials可以遵循不同的路径,如_partials/Header.twig.html,并且您可以使用变量在模板中包含它们,如{% include '_partials/Header.twig.html' with {bar: 'foo'}%}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接