使用 Twig 从 parent 模板访问 child 模板中的变量集
Accessing a variable set in a child template from the parent template with Twig
我的模板中有以下设置。我有很多这样的 child 模板,其中 subject
块每次都不一样。
有没有办法让我从 parent 访问 child 中设置的 subjectTitle
变量?
Parent:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width"/>
</head>
<body>
<span style="display: none !important;">{{ preHeader }}</span>
Child:
{% extends 'CRMPiccoMailerBundle:Email:base.html.twig' %}
{% block subject %}
{% set subjectTitle = 'Thanks for ordering! Your Order is 1872.' %}
{{ subjectTitle }}
{% endblock %}
获得所需结果的最佳方法是在父模板上创建一个空的 block
,然后在子模板上设置它的值。
是的,您可以像访问任何其他变量一样访问这些变量。请务必检查其是否已定义并正确流动。
示例
我使用子变量的一种方式是用于样式表:
base.html.twig
<html>
<head>
<link href="css/{{ style|default('base') }}.css" rel="stylesheet" />
</head>
<body>
{% if style is not defined %}
<p>Default style applied</p>
{% else %}
<p>Styling!</p>
{% endif %}
<!-- content here -->
</body>
</html>
contact.html.twig
{% extends 'base.html.twig' %}
{% set style = 'contact' %}
...
在head部分,我用了一个macro for checking the variable and showing a default value if it was undefined (this only works in version 1.12+). If the child template defines the variable, it will use its value otherwise it defaults to the base style sheet. But in the body I show the older way using tags。根据变量是否定义,决定输出哪一段。
我的模板中有以下设置。我有很多这样的 child 模板,其中 subject
块每次都不一样。
有没有办法让我从 parent 访问 child 中设置的 subjectTitle
变量?
Parent:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width"/>
</head>
<body>
<span style="display: none !important;">{{ preHeader }}</span>
Child:
{% extends 'CRMPiccoMailerBundle:Email:base.html.twig' %}
{% block subject %}
{% set subjectTitle = 'Thanks for ordering! Your Order is 1872.' %}
{{ subjectTitle }}
{% endblock %}
获得所需结果的最佳方法是在父模板上创建一个空的 block
,然后在子模板上设置它的值。
是的,您可以像访问任何其他变量一样访问这些变量。请务必检查其是否已定义并正确流动。
示例
我使用子变量的一种方式是用于样式表:
base.html.twig
<html>
<head>
<link href="css/{{ style|default('base') }}.css" rel="stylesheet" />
</head>
<body>
{% if style is not defined %}
<p>Default style applied</p>
{% else %}
<p>Styling!</p>
{% endif %}
<!-- content here -->
</body>
</html>
contact.html.twig
{% extends 'base.html.twig' %}
{% set style = 'contact' %}
...
在head部分,我用了一个macro for checking the variable and showing a default value if it was undefined (this only works in version 1.12+). If the child template defines the variable, it will use its value otherwise it defaults to the base style sheet. But in the body I show the older way using tags。根据变量是否定义,决定输出哪一段。