[英]Render a block of a “parent” template from a “child” template in Twig
我有两个模板:
Fields.html.twig ,其中包括一个子模板。
{% block important %}
This block should be renderable from the sub template
{% endblock important %}
{% include 'XButton.html.twig' %}
XButton.html.twig ,需要呈现在包含它的模板中定义的块。
block('important')
似乎包含的模板无法简单地渲染包含它的对象的块。
父级模板如何将完整的上下文传递给子级,以便子级可以访问父级中定义的块?
您尝试执行的操作是不可能的,因为包含的模板无法了解其他模板中定义的块...
您需要对代码的结构进行一些改动,以便以某种方式在父级中定义块的内容-至少有两个选择:
set
和include
: https : //twigfiddle.com/l536np Fields.html.twig
{% set important %}
You define the child content as a variable in the parent...
{% endset %}
{% include 'XButton.html.twig' %}
XButton.html.twig
{{ important }}
embed
: https : //twigfiddle.com/y9pp6p Fields.html.twig
{% embed 'XButton.html.twig' %}
{% block important %}
You define the block content in the parent...
{% endblock %}
{% endembed %}
XButton.html.twig
{{ block('important') }}
您可以通过传递父模板名称来实现包含
{% block important %}
This block should be renderable from the sub template
{% endblock important %}
{% include 'XButton.html.twig' with {'parent': _self} %}
然后在包含模板中使用它
{{ block('important', parent) }}
尽管通过这种方式,该块的内容将呈现两次-一次是在父级中定义,一次是在子级中-请参见https://twigfiddle.com/6t0l6p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.