Reputation: 1389
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
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