我想在Twig做类似的事情:
{% inlinetemplate input_wrapper %}
<div class="control-group">
<label class="control-label" for="{% block name %}{% endblock name %}">
{% block label %}{% endblock label %}
</label>
<div class="controls">
{% block controls %}{% endblock controls %}
</div>
</div>
{% endinlinetemplate %}
{% extendinline input_wrapper %}
{% block label %}Age {% endblock label %}
{% block name %}age{% endblock name %}
{% block controls %}
<select name="age">
<option ...>...</option>
...
</select>
{% endblock controls %}
{% endextendline input_wrapper %}
这可能吗?
答案 0 :(得分:7)
根据您对实际需求的评论,我认为set tag的“块版本”是您所需要的,即:
{% set variableName %}
<p>
Content block with <i>line-breaks</i>
and {{ whatever }} else you need.
</p>
{% endset %}
然后,您需要的任何标记块都可以传递给宏(正如其他人所建议的那样):
{% macro input_wrapper(label, name, controls) %}
<div class="control-group">
<label class="control-label" for="{{ name }}">{{ label }}</label>
<div class="controls">{{ controls }}</div>
</div>
{% endmacro %}
{% set label, name = "Age", "age" %}
{% set controls %}
<select name="age">
<option>...</option>
</select>
{% endset %}
{% import _self as inline %}
{{ inline.input_wrapper(label, name, controls) }}
至于原始问题,我做了一些研究,发现你可以定义内嵌模板,结合set和verbatim标记加上template_from_string功能。
模板的内容取决于您希望使用的方式:
{# Defining the template #}
{% set input_wrapper_string %}
{% verbatim %}
<div class="control-group">
<label class="control-label" for="{{ name }}">{{ label }}</label>
<div class="controls">{{ controls }}</div>
</div>
{% endverbatim %}
{% endset %}
{% set input_wrapper_tpl = template_from_string(input_wrapper_string) %}
{# Setting the variables #}
{% set label, name = "Age3", "age" %}
{% set controls %}
<select name="age">
<option>...</option>
</select>
{% endset %}
{# "Rendering" the template #}
{% include input_wrapper_tpl %}
{# Defining the template #}
{% set input_wrapper_string %}
{% verbatim %}
<div class="control-group">
<label class="control-label" for="{% block name %}{% endblock %}">{% block label %}{% endblock %}</label>
<div class="controls">{% block controls %}{% endblock %}</div>
</div>
{% endverbatim %}
{% endset %}
{% set input_wrapper_tpl = template_from_string(input_wrapper_string) %}
{# "Rendering" the template and overriding the blocks #}
{% embed input_wrapper_tpl %}
{% block label %}Age{% endblock %}
{% block name %}age{% endblock %}
{% block controls %}
<select name="age">
<option>...</option>
</select>
{% endblock %}
{% endembed %}
答案 1 :(得分:0)
如果使用Symfony 2,您可以使用嵌入控制器(http://symfony.com/doc/current/book/templating.html)或包含其他模板。模板继承也可以帮助您定义通用块。