无法覆盖包含的树枝模板中的块 [英] Cant override blocks in included twig template
问题描述
请帮助我理解在 twig 中使用模板继承的正确方法.
Please help me understand the right way to use template inheritance in twig.
我有一个模板 base.html.twig,我的所有其他模板都扩展了它.这包含 html、head、body 等标签和一些块.
I have a template base.html.twig that all my other templates extend. This contains the html, head, body, etc. tags and a few blocks.
我想移动 <head > 部分从 base.html.twig 模板到它自己的文件 head.html.twig.如果我使用 include 指令,则该部分中的标题块将不再被扩展模板正确覆盖.
I would like to move the < head > section from the base.html.twig template into its own file head.html.twig. If I use the include directive then the title block in that section no longer gets overridden properly by the extending templates.
我确定我可以通过将标题设置为扩展模板中的变量并将其传递到我的 include 语句中来解决此问题.但是现在我的页面需要在 < 中加载额外的 javascript 位.head > 部分,因此我必须添加变量以指示要加载哪些变量...
I determined that I could work around this by setting the title as a variable in the extending template and passing it in my include statement. But now I have pages that need extra bits of javascript loaded in the < head > section, so I have to add variables to indicate which of those to load...
显然这是一个可怕的混杂.这样做的正确方法是什么?
Obviously this is a horrible kludge. What is the right way to do this?
在@goto 的建议下,我尝试将 include 替换为 embed.现在我的代码看起来像:
At the suggestion of @goto I tried replacing include with embed. Now my code looks like:
{# base.html.twig #}
<!DOCTYPE html>
<html>
{% embed 'AppBundle::head.html.twig' %}
{% block title %}My Company Name{% endblock %}
{% endembed %}
<body>
{% block content %}{% endblock %}
</body>
</html>
{# head.html.twig #}
<head>
<title>{% block title %}{% endblock %}</title>
<!-- load other css, js, etc -->
</head>
{# page.html.twig #}
{% extends 'AppBundle::base.html.twig' %}
{% block title %}{{ page.title }} - My Company Name{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
{{ page.content|raw }}
{% endblock %}
但这不起作用,标题总是我的公司名称".
But this doesnt work, the title is always "My Company Name".
推荐答案
找到了解决方案.我需要使用"标签:
Found the solution. I needed the "use" tag:
{# base.html.twig #}
<!DOCTYPE html>
<html>
{% use 'AppBundle::head.html.twig' %}
{% block head %}
{{ parent() }}
{% endblock %}
<body>
{% block content %}{% endblock %}
</body>
</html>
{# head.html.twig #}
{% block head %}
<head>
<title>{% block title %}My Company Name{% endblock %}</title>
<!-- load other css, js, etc -->
</head>
{% endblock %}
{# page.html.twig #}
{% extends 'AppBundle::base.html.twig' %}
{% block title %}{{ page.title }} - My Company Name{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
{{ page.content|raw }}
{% endblock %}
这篇关于无法覆盖包含的树枝模板中的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!