我正在使用Twig构建模板。我想知道处理具有多个条件的if语句的最快/最好方法是什么。
我们说我有3个图像,有3个可能的位置。通常我会这样做:
{% 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 %}
等...
有更快/更清洁的方法吗?我无法弄清楚如何做到这一点。
答案 0 :(得分:1)
试试这个:
{% set model_position = image1 in ['centerleft', 'topleft', 'bottomleft'] ? 'right': 'left' %}
等等......
修改 - 说明:
我使用ternary operator
获取left
或right
,具体取决于条件。 in
是Twig
' containment operator
,其工作方式与PHP中的in_array
函数类似
因此,如果image1
属于centerleft
,topleft
或bottomleft
,则为right
,其他为left