Search code examples
phptemplatestwigcode-readability

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!


Solution

  • Use Twig's default filter:

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