Meules
Meules

Reputation: 1389

Multiple conditions in Twig

I'm building a template with Twig. I was wondering what the fastest/best way is to deal with an if statement with multiple conditions.

Let's say I have 3 Images with 3 possible positions. Normally I would do this:

{% if image1 == 'centerleft' or 'topleft' or 'bottomleft' %}
{% set model_position = 'right' %}{% else %}{% set model_position = 'left' %}
{% endif %}

{% if image2 == 'centerleft' or 'topleft' or 'bottomleft' %}
{% set model_position = 'right' %}{% else %}{% set model_position = 'left' %}
{% endif %}

etc....

Is there a faster/cleaner way to do this? I can't figure out how to do that.

Upvotes: 1

Views: 750

Answers (1)

Bartek
Bartek

Reputation: 1359

Try with this:

{% set model_position = image1 in ['centerleft', 'topleft', 'bottomleft'] ? 'right': 'left' %}

And so on...

edit - explanation:

I'm using ternary operator to get either left or right depending on the condition. in is Twig's containment operator and works like in_array function in PHP

So, if image1 is one of centerleft, topleft or bottomleft then right, else left

Upvotes: 1

Related Questions