Django模板——模板标签

Django模板——模板标签 1

1.简介

1.1用途

​ 解决硬编码问题,提高灵活性,方便项目管理。

1.2语法

标签语法: 由{%和 %} 来定义的,例如:{%tag%} {%endtag%}

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.py

    #book/views  book是App名称
    def hello(request):
        return render(request, 'hello.html')
    
    #index方法需要捕获参数
    def index(request, sti_id):
        return render(request, 'index.html')
  • xxx.html

     <!--格式:{% 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 %}

学生姓名为:danny

2.7 注释标签

2.8 autoescape标签

<!--
转义标签,
取html="<b>东强出品,必属精品</b>"
-->
原始:{{ html }} <br/ >
过滤器:{{ html|safe }}<br/ >
标签:
{% autoescape off %}<br/ >
    {{ html }}
{% endautoescape %}

原始:<b>东强出品,必属精品<b>
过滤器:东强出品,必属精品
标签:东强出品,必属精品


  1. 东强出品,必属精品!

猜你喜欢

转载自www.cnblogs.com/it-sunshine/p/10526990.html