Learn how to conditionally print a variable or some placeholder value if it's empty.

Twig usually makes the things easier for developers and designers, you can print some data sent from a controller in the view using a very simple and easy to understand syntax, however sometimes this syntax (when you are a developer) can be a little bit lame if the thing that you want to achieve is very simple. For example, printing a simple value conditionally with a placeholder. Imagine an object namely article, this article object has the property visits that can be an integer (number of visits or null). So, when you write the normal twig syntax to print the value 0 if the visits property is null, the code would be:

{% if article.visits %}
    {{ article.visits }}
{% else %}
    0
{% endif %}

The code works perfectly and would print either the original number of visits or 0 if the value is null, however took 5 lines of your file to print the value. Using the ternary operator (shorthand syntax), you can easily print a value if exists or use a placeholder in case that the variable is empty, for example, with our example the code would be instead:

{{ not article.visits ? "0" : article.visits }}

Which express the same logic with the sample above, if article.visits is null, print 0, otherwise prints its original value. We would like invite you as well, to read 10 twig tips that every developer should know, as you may find useful tips like this.

Using the default filter

If the previous syntax still even long for you, then you can use the default filter that returns the value of the filtered variable if it is not empty, if it's empty, then the argument provided in the filter will be used that in this case is 0:

{{ article.visits|default("0")}}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors