Format a CSV string in Twig

If you’ve ever had to format a string of values in most languages then you’re certainly familiar with the ugly logical hoops you have to jump through just to get the formatting to look good.

Here’s a nice way to do it in Twig:

So given a dirty array of phone numbers:

['123-4567', '', '321-7654']

the above snippet will strip empty values, chomp extraneous whitespace, and output:

Phones: 123-4567, 321-7654

Simple Twig Fallback

Love the simplicity of Twig; mainly that it allows us to do away with the conditionals that tend to litter most interface code.  You know the drill: If this then show that otherwise show the other thing except in such-and-such a case..  Confusing and brittle.  Twig’s hierarchical layout is the way to go.

Falling back to a parent block depending on complex output can be tricky however.  Here’s a simple way to do it without a bunch of ifs:

Yay. If less.

Or with one ternary conditional if running parent() through default() is unclear:

{{ details|trim|raw ?: parent() }}

Not Defined and Not Empty/Null in Twig

Long time no write.  Came across some syntax today that solves an old annoyance in Symfony's Twig.

Rather than blather on in code with the following complex statement to make sure that a value is both defined and not null:

{% if var is defined and var is not null %}

one can instead simply do this:

{% if var|default is not empty %}

or even more simply:

{% if var|default %}