Twig:包含另一个模板的块

tun*_*ten 6 symfony twig

我想只包含另一个模板的某些块的内容.是否可以只访问块的内容而不是整个文件?

据我所知,embedinclude始终包含并输出整个文件.并且use导入所有块并且显然(?)目标文件需要硬编码,并且不能是传递给模板的表达式或变量.那是对的吗?

alb*_*ert 8

使用宏https://twig.symfony.com/doc/2.x/tags/macro.html

渲染块模板(由web profiler使用):https://twig.symfony.com/doc/2.x/functions/block.html

{{ block("title", "common_blocks.twig") }}
Run Code Online (Sandbox Code Playgroud)

Symfony WebProfiler - 块和模板的有趣用法

Symfony WebProfiler就是一个很好的例子:

供应商/ symfony中/ symfony中/ src目录/ Symfony的/包/ WebProfilerBundle /资源/视图/收集/ request.html.twig

每个探查器视图模板都有3个块:

  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 -->
Run Code Online (Sandbox Code Playgroud)