MisterQuacker MisterQuacker - 3 months ago 13
Twig Question

Making Twig filter to assign defaults unless otherwise specified

I'm trying to use twig as a template system for my website. I'm wanting to write something along the lines of...

{{ title }}
{% pageAuthor | Unknown %}


I would like "Unknown" to become the default value if pageAuthor is empty. I could use a bunch of "if" statements but that would hurt readability. This is clean and easy to write. Thanks for any help!

Answer

Use Twig's default filter:

{{ pageAuthor|default('Unknown') }}
Comments