Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to call an imported macro dynamicly #922

Closed
chasen opened this issue Dec 6, 2012 · 3 comments
Closed

Ability to call an imported macro dynamicly #922

chasen opened this issue Dec 6, 2012 · 3 comments

Comments

@chasen
Copy link

chasen commented Dec 6, 2012

I am attempting to use a variable to call a specific macro name.

I have a macros file that is being imported

{% import 'form-elements.html.twig' as forms %}

Now in that file there are all the form element macros: text, textarea, select, radio etc.

I have an array variable that gets passed in that has an elements in it:

$elements = array(
array(
'type'=>'text,
'value'=>'some value',
'atts'=>null,
),
array(
'type'=>'text,
'value'=>'some other value',
'atts'=>null,
),
);

{{ elements }}

what im trying to do is generate those elements from the macros. they work just fine when called by name:

{{ forms'text' }}

However what i want to do is something like this:

{% for element in elements %}
{{ formselement.type }}
{% endfor %}

This unfortunately throws the following error:

Fatal error: Uncaught exception 'LogicException' with message 'Attribute "value" does not exist for Node "Twig_Node_Expression_GetAttr".' in Twig\Environment.php on line 541

Any help or advice on a solution or a better schema to use would be very helpful.

@fabpot
Copy link
Contributor

fabpot commented Dec 7, 2012

This is indeed something that is not supported: calling a macro with a dynamic name (I have added a proper exception to be clearer about the issue).

If you really want to do that, you can do so with the following code:

{{ attribute(forms, element.type, [element.name,element.value,element.atts]) }}

@fabpot fabpot closed this as completed Dec 7, 2012
@chasen
Copy link
Author

chasen commented Dec 7, 2012

Thanks for your quick reply, and your help in pointing me in the right direction.

@dueddel
Copy link

dueddel commented May 3, 2019

It's not necessary to "hack" your way to dynamically call macros or anything like that. There's a pretty simple workaround described at Stack Overflow.

You basically have to (dynamically) include templates which (statically) call the macros.
See https://stackoverflow.com/a/55970814/3773017 for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants