marcosh
marcosh

Reputation: 9008

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?

Upvotes: 13

Views: 288

Answers (1)

Chase
Chase

Reputation: 9362

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.

Upvotes: 5

Related Questions