Why Twig Rules
The more I use Twig, the PHP templating language, the more I discover its power and simplicity. Moments that would be a slog in PHP (especially in your HTML, ugh!) become invisible with Twig.
Let’s say you have a variable, but you don’t know whether it has been set for your view. The data may or may not be there. It might have never been defined in the first place.
In PHP, you would check to see if it is set and not empty:
Similarly in Twig, you could check in the same (but more wordy) way:
But wait, Twig has a filter called default
, that will return a default value for a variable that is not set.
Here the default value is set to nothing:
Better, right? Well, yes, better, but not the best.
Looking back at default
, it is actually a wrapper for both defined
and empty
. This means we don’t need to check if the variable has value since it is already being checked.
This is why Twig rules: