Question

Is there a smart way to display/use a twig variable only if it exists?

Say, I've got a structure:

'opt1': {'visible': false, 'bundle': 'XxxBundle', 'name': 'label1'},
'opt2': {'visible': true, 'bundle': 'YyyBundle', 'name': 'label2', 'params': '/par1'},

and I use it in:

<a href="{{path(desc.bundle ~ '_' ~ action ~ desc.params)}}">

I would like twig to omit desc.params if it doesn't exist for distinct entry. Is there any smarter way than using if statement?

Was it helpful?

Solution

You could just pass a default blank string to it.

<a href="{{path(desc.bundle ~ '_' ~ action ~ desc.params|default(''))}}">

This way if its not defined its just an empty string. You can read more about the default filter here: http://twig.sensiolabs.org/doc/filters/default.html

OTHER TIPS

Another solution is to set strict_variables to false in you config.yml file:

twig:
    ...
    strict_variables: false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top