source

twig: 여러 조건이 있는 경우

factcode 2023. 1. 15. 17:15
반응형

twig: 여러 조건이 있는 경우

잔가지 if 스테이트먼트에 문제가 있는 것 같습니다.

{%if fields | length > 0 || trans_fields | length > 0 -%}

에러는 다음과 같습니다.

Unexpected token "punctuation" of value "|" ("name" expected) in 

이게 왜 작동하지 않는지 이해가 안 가. 마치 나뭇가지가 파이프와 함께 없어진 것 같아.

저도 해봤어요

{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}

if도 실패합니다.

그 후, 다음과 같이 해 보았다.

{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}

그런데도 동작하지 않고, 매번 같은 에러가 발생합니다.

그래서 아주 간단한 질문으로 이어지죠. Twig는 여러 조건을 지원하나요?

내 기억이 맞다면 Twig는 지원하지 않는다.||그리고.&&연산자(단, 필수)or그리고.and사용할 수 있습니다.또, 이것은 엄밀히 말하면 필수는 아니지만, 2개의 문구를 보다 명확하게 나타내기 위해서 괄호를 사용합니다.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

표현.

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

보다 복잡한 조작의 경우는, 개개의 식을 괄호로 둘러싸 혼동을 회피하는 것이 최선입니다.

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

사용.!=여러 가지 조건이 있기 때문에 저도 마찬가지입니다만,==동작합니다.실제로 이건 버그 같아요.

회피책일 수 있습니다.

{% if key not in ['string1', 'string2'] %}
// print something
{% endif %}

언급URL : https://stackoverflow.com/questions/8388537/twig-if-with-multiple-conditions

반응형