Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve variable name in Twig

I am using Twig templating engine an I would like to create a filter

{{ my_variable|default_variable }}

that returns the name of the variable (in this case, the string "my_variable") when the variable is empty. Is this possible? How can I retrieve the name of the variable and not its value?

like image 678
marcosh Avatar asked Jul 09 '14 15:07

marcosh


1 Answers

I dont know that it is possible, you could pass the name you want to use as an argument to the filter

{{ my_variable|default_variable('my_variable') }}

then your filter:

$filter = new Twig_SimpleFilter('default_variable', function ($value, $defaultName) {
    return (String)$value?:$defaultName;
});

That will return the string version of the value of your variable or if it cant then the default name.

like image 199
Chase Avatar answered Sep 28 '22 16:09

Chase