LoginSignup
5
4

【Twig】条件分岐の使い方

Last updated at Posted at 2023-05-14

Twigの条件分岐について備忘録的にまとめてみました。

if 文の書き方から

{% if foo %}
  AAA
{% elseif %}
  BBB
{% else %}
  CCC
{% endif %}

論理演算子

AND 条件

{% if hoge and fuga %}
  {{ hoge }} / {{ fuga }}
{% endif %}

OR 条件

{% if hoge or fuga %}
  {{ hoge }} {{ fuga }}
{% endif %}

比較演算子

== , != , < , > , <= , >=等の比較演算子は使用可能。

正規表現

{% if phone matches '/^[\\d\\.]+$/' %}
  {{ phone }}
{% endif %}

厳密等価演算子

=== , !=== は使用不可。

{% if foo is same as(false) %}
  {{ foo }}
{% endif %}

三項演算子

{{ foo ? 'yes' : 'no' }}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

null合体演算子

{{ foo ?? 'no' }}

その他のオペレーター

in_array 関数

配列内の要素が含まれているかのチェックなどなど。

{{ 1 in [1, 2, 3] }}

{# 配列ではないけど...。文字列チェックもできるようですね。 #}
{{ 'cd' in 'abcde' }}

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4