Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig: display variable only if it exists

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?

like image 225
ducin Avatar asked Mar 08 '13 10:03

ducin


2 Answers

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

like image 171
Chase Avatar answered Dec 28 '22 12:12

Chase


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

twig:
    ...
    strict_variables: false
like image 20
Thomas K Avatar answered Dec 28 '22 14:12

Thomas K