Jinja If: 基本的な if ステートメント
Jinja2ifステートメント
Jinja2 の if ステートメントは、テンプレート内の条件付きロジックの基本的な制御構造です。これにより、条件が true か false に基づいてコンテンツを選択的にレンダリングできます。 Jinja2 では、変数は空ではなく定義されている場合に「真実」であるとみなされます。
基本的な if ステートメント
最も一般的な使用例は、変数に値があるかどうかを確認することです。ブロック内のコードは、変数が空ではない場合 (空ではないリストや文字列など) にのみレンダリングされます。
text
{% if users %} Users found.
{% for user in users %}
{{ user.username|e }}
{% endfor %}
{% endif %}
「if...else」と「elif」
初期条件が false の場合は、「else」ブロックを使用して代替を提供します。複数の条件の場合は、それらを `elif` で連結します。
text
{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %} {% if user.role == 'admin' %}
Admin dashboard.
{% elif user.role == 'editor' %}
Editor tools.
{% else %}
User profile.
{% endif %}
共通テストと演算子
論理演算子 (「and」、「or」、「not」) を使用して条件を結合したり、「define」、「none」、「empty」などの組み込みテストで「is」演算子を使用したりできます。
text
{% if my_variable is defined and my_variable is not none %}
The variable is defined and has a value.
{% endif %} {% if articles is empty %}
No articles to display.
{% endif %} {% if user.is_authenticated and user.country == 'US' %}
US-specific content.
{% endif %}
ジャンプ