Twig conditionals
Code
When you use a custom field solution like ACF or Meta Box you will want to output the data that you have entered. But sometimes, conditions apply so that the output changes.
Let’s take a post in which we advertise items at a certain price. But for some items, prices change on a daily basis and we want people to call when no price is given:
{% if post.price %}
<h3>Price is $ {{ post.price }}</h3>
{% else %}
<h3>Please call for latest price!</h3>
{% endif %}
As you can see, we apply an if .. else
structure here.
We could also write it a little shorter:
{% if post.price %}<h3>Price is $ {{ post.price }}</h3>{% else %}<h3>Please call for latest price!</h3>{% endif %}
{#
or
#}
<h3>{% if post.price %}Price is $ {{ post.price }}{% else %}Please call for latest price!{% endif %}</h3>
Or using the ternary operator:
<h3>{{ post.price ? "price is $ " ~ post.price : "Please call for latest price!" }}</h3>
The ternary operator is “condition ? x : y”, meaning “if CONDITION is true, return X, if not return Y”. In our case, whenever post.price is true it will display the price and if not, it displays the text.
Very short ternary operator usage
Twig is all about trying to write short, readable templates. So if writing out long if .. else .. endif operators can be avoided, please do. In Twig the ternary operator is very efficient:
{{ post.price ?:'-' }}
{#
is the same as:
#}
{{ post.price ? post.price : '-' }}
This, for instance, checks if we have a value post.price (the condition), and it returns that value post.price as the X. If there is no post.price, it will return a dash (Y).
Beaverplugins
Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife.Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.