Dynamically invoke macros in Twig?

Is it possible to dynamically invoke a macro in Twig? For example, here is a template and macro called "group" that creates a group of buttons using the buttons array argument. There are also two other macros: save and delete to create save and delete buttons.

 {# 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 %} 

This works fine with array buttons:

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

But I would like to pass macros to group macro:

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

and automatically invoke save and delete macros. Is this possible and how?

+4
source share
2 answers

why not just do

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

For those looking for an example of implementing a dynamic macro call using an attribute, check out https://gist.github.com/tentacode/9728963b9f3a714608f3

0
source

Source: https://habr.com/ru/post/1399658/


All Articles