How to access to macro dynamically in Twig template?

Oct 14, 2014 22:04


Originally published at ostretsov.ru. You can comment here or there.

You may access to macro dynamically in Twig but this solution is risky. This method will’t ever be in best practice guidebook. But… It works.

Every Twig template is compiled to common PHP file and every macro converted to public method. For example, this foo macro:

{% import _self as _util %} {% macro some_method(param) %} {{ param }} {% endmacro %}
is compiled to something like this:

// line 10 public function getsome_method($_param = null) { $context = $this->env->mergeGlobals(array( "param" => $_param, )); $blocks = array(); ob_start(); // ...
As you may know it is possible to access public method with attribute Twig-function. So, solution will be like this:

{% set macro_name = 'some_method' %} {{ attribute(_util, 'get' ~ macro_name, [param]) }}

hints

Previous post Next post
Up