code

조건부 텍스트를 출력하는 Twig 속기 구문이 있습니까?

codestyles 2020. 12. 10. 20:19
반응형

조건부 텍스트를 출력하는 Twig 속기 구문이 있습니까?


Twig에 조건부 텍스트 문자열을 출력하는 더 짧은 구문이 있습니까?

<h1>{% if not info.id %}create{% else %}edit{% endif %}</h1>

전통적인 PHP는 이것보다 훨씬 쉽습니다.

<h1><?php info['id']? 'create' : 'edit' ?></h1>

이것은 작동합니다.

{{ not info.id ? 'create' : 'edit' }}

또한 이것을 삼항 연산자라고합니다. 문서에 숨겨져 있습니다 : twig docs : operator

문서에서 기본 구조는 다음과 같습니다.

{{ foo ? 'yes' : 'no' }}

값을 비교해야하는 경우 다음을 수행 할 수 있습니다.

{{  user.role == 'admin' ? 'is-admin' : 'not-admin' }}

나뭇 가지 안에 Elvis 연산자를 사용할 수 있습니다.

{{  user ? 'is-user' }} 

{{  user ?: 'not-user' }} // note that it evaluates to the left operand if true ( returns the user ) and right if not

널 병합 연산자 도 같은 작업 :

{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}

참고 URL : https://stackoverflow.com/questions/13336090/is-there-a-twig-shorthand-syntax-for-outputting-conditional-text

반응형