[TOC]html
Django模板——模板標籤 ^^_^
1.簡介
1.1用途
解決硬編碼問題,提升靈活性,方便項目管理。python
1.2語法
標籤語法: 由{%和 %} 來定義的,例如:{%tag%} {%endtag%}app
1.3常見標籤
2.標籤詳解
2.1 if/else 標籤
{% if condition1 %} ... display 1 {% elif condition2 %} ... display 2 {% else %} ... display 3 {% endif %} <!-- 根據條件判斷是否輸出。if/else 支持嵌套。 接受 and , or 或者 not 等關鍵字來對多個變量作判斷 -->
2.2 for 標籤
<!-- {% for %} 容許咱們在一個序列上迭代。 與Python的 for 語句的情形相似,循環語法是 for item in iterator。 每一次循環中,模板系統會渲染在 {% for %} 和 {% endfor %} 之間的全部內容。 --> <ul> {% for item in iterator %} <li>{{ item.name }}</li> {% endfor %} </ul> <!-- 給標籤增長一個 reversed 使得該列表被反向迭代: --> {% for item in iterator reversed %} ... {% endfor %} <!-- 能夠嵌套使用 {% for %} 標籤: --> {% for item in iterator %} <h1>{{ item.name }}</h1> <ul> {% for stu in item.students %} <li>{{ stu }}</li> {% endfor %} </ul> {% endfor %}
2.3 ifequal/ifnotequal 標籤
<!-- {% ifequal %} 標籤比較兩個值,當他們相等時,顯示在 {% ifequal %} 和 {% endifequal %} 之中全部的值。 --> {% ifequal gender 1 %} <h1>Welcome to my vilage, girl!</h1> {% endifequal %} <!-- {% ifequal %} 支持可選的 {% else%} 標籤 --> {% ifequal name 'danny' %} <h1>hello danny</h1> {% else %} <h1>hello LiMing</h1> {% endifequal %}
2.4 include 標籤
<!-- {% include %} 標籤容許在模板中包含其它的模板的內容. --> {% include "hello.html" %}
2.5 url標籤
-
urls.py編碼
#book/urls book是App名稱 app_name = 'book' urlpatterns = [ #標籤經過路由表中name參數值,重定向到模板文件。 path('hello/', views.hello, name='hello'), path('index/<stu_id>/', views.index, name='index') ]
-
views.pyurl
#book/views book是App名稱 def hello(request): return render(request, 'hello.html') #index方法須要捕獲參數 def index(request, sti_id): return render(request, 'index.html')
-
xxx.htmlspa
<!--格式:{% url '模板文件' %}--> <li><a href="{% url 'book:hello' %}">welcome</a></li> <!--如需追加參數文件名後使用:空格 + 實參便可,即:變量名[空格+parm1][空格+parm2...]--> <li><a href="{% url 'book:index' 12 %}">index</a></li>
2.6 with 標籤
<!-- 重命名標籤,相似python中:with...as... 取student.name=danny --> {% with student.name as sname %} {# 將student.name重命名爲sname #} 學生姓名爲:{{ sname }} {% endwith %}
學生姓名爲:dannycode
2.7 註釋標籤
2.8 autoescape標籤
<!-- 轉義標籤, 取html="<b>東強出品,必屬精品</b>" --> 原始:{{ html }} <br/ > 過濾器:{{ html|safe }}<br/ > 標籤: {% autoescape off %}<br/ > {{ html }} {% endautoescape %}
原始:<b>東強出品,必屬精品<b> 過濾器:東強出品,必屬精品 標籤:東強出品,必屬精品htm