twigphp / Twig

Twig, the flexible, fast, and secure template language for PHP
https://twig.symfony.com/
BSD 3-Clause "New" or "Revised" License
8.16k stars 1.25k forks source link

"Try values" chain - more advanced then |default(...) #713

Closed meglio closed 12 years ago

meglio commented 12 years ago

We currently have default(...) filter in Twig.

In PHPTAL howerver there is something beautiful and sometimes very useful to try few values in order of priority, for example:

<div tal:attributes="class var1|var2|var3|nothing/>

Here there are 2 interesting features:

1. It will try var1. If var1 is not defined then it will try var2 and so on. If even var3 is not defined - it will put empty string (nothing is just keyword for a void value). NB. If var1 is defined and empty - it will use its value - eg empty value.

It would be useful to have similar feature in Twig, where last variation can also be default(...) filter.

I'm not sure what syntax is best. But it will look ugly to use function-like style:

{% try(expr1, expr2)|default(...)  %}

Instead something more readable preferred, maybe:

{{ expr1 || expr2 || expr3 | default(...) }}

2. "nothing" special keyword. Is there something in twig to use instead of default('')?

fabpot commented 12 years ago

So, here is the equivalent in Twig:

{{ expr1|default(expr2|default(expr3|default(''))) }}

'' being the exact equivalent of nothing.

I think the use case where you have many variables to test is pretty rare and probably not worth a new function/syntax. Django and Jinja do not have such support.