我想在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 %}
这可能吗?
快速解决方案
根据你对你真正想要的东西的评论,我相信set标签的"块版本"是你需要的,即:
{% 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) }}
真正的解决方案
至于最初的问题,我做了一些研究,发现您可以通过集合和逐字标记的组合以及template_from_string函数来定义内联模板。
但是,模板的内容取决于您想要如何使用它:
- 如果您对使用块语法设置变量感到满意,请使用include标记或函数
- 如果您需要使用块,就像在您的原始示例中一样,您将不得不使用嵌入标记
使用变量和include标记的示例
{# 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 %}
如果使用Symfony 2,则可以使用嵌入式控制器(http://symfony.com/doc/current/book/templating.html)或者包括其他模板。此外,模板继承可以帮助您定义常规块。