动态调用Twig中的宏?

时间:2012-03-04 15:49:45

标签: symfony twig

可以在Twig中动态调用宏吗?例如,这是一个模板和一个名为“group”的宏,它使用buttons array参数构建一个按钮组。还有另外两个宏savedelete,用于构建保存和删除按钮。

{# Make a group of buttons #}
{% macro group(buttons) %}
{% spaceless %}
    {% import "::macros.html.twig" as macros %}

    {% set content = '' %}

    {% for button in buttons %}
        {% set content = content ~ button %}
    {% endfor %}

    {{ macros.el('div', content, { 'class' : 'btn-group' }) }}
{% endspaceless %}
{% endmacro %}

{# Make a save button #}
{% macro save(attributes, size, image) %}
{% spaceless %}
    {{ _self.primary('save'|trans({}, 'buttons'), attributes, size, image) }}
{% endspaceless %}
{% endmacro %}

{# Make a delete button #}
{% macro delete(attributes, size, image) %}
{% spaceless %}
    {{ _self.danger('delete'|trans({}, 'buttons'), attributes, size, image) }}
{% endspaceless %}
{% endmacro %}

这可以很好地传递array个按钮:

{% import "::buttons.html.twig" as buttons %}
{% set items = [buttons.save, buttons.delete] %}
{{ buttons.group(items) }}

但我想将宏名称传递给group宏:

{% import "::buttons.html.twig" as buttons %}
{{ buttons.group(['save', 'delete']) }}

并自动调用savedelete个宏。这可能吗?如何?

2 个答案:

答案 0 :(得分:0)

为什么不做呢

{% import "::buttons.html.twig" as buttons %}
{{ buttons.group([buttons.save, buttons.delete]) }}

答案 1 :(得分:0)

对于那些寻找如何使用属性实现动态宏调用的示例的人,checkout https://gist.github.com/tentacode/9728963b9f3a714608f3