django html 如何寫 if 判斷?
在 Django 的 HTML 模板中,要使用 if 判斷可以這樣寫(語法類似 Python,但用 {% %} 包起來):
✅ 基本寫法
{% if 條件 %}
顯示的內容
{% endif %}
✅ 範例:判斷變數是否存在或為 True
{% if user.is_authenticated %}
歡迎,{{ user.username }}
{% else %}
請先登入
{% endif %}
✅ 判斷是否為空或為 0
{% if logs %}
有操作紀錄
{% else %}
沒有資料
{% endif %}
✅ 判斷相等、不相等、大小比較
{% if log.uid == 'admin' %}
管理者操作
{% endif %}
{% if value != 0 %}
非零數值
{% endif %}
{% if count > 10 %}
超過十筆資料
{% endif %}
✅ 多重條件(and、or)
{% if user.is_staff and user.is_active %}
員工帳號啟用中
{% endif %}
{% if user.is_superuser or user.username == 'admin' %}
超級權限使用者
{% endif %}
✅ 用 in 判斷是否包含在清單中
{% if 'admin' in user_roles %}
有管理員權限
{% endif %}

留言板
歡迎留下建議與分享!希望一起交流!感恩!