Django4:模板—常用的标签介绍_django4 标签语法,Golang入门视频教程
    		       		warning:
    		            这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
    		        
        		                
                在Django中,模板标签用于在模板中插入动态内容。标签通常以"%"开头,以"%"结尾。
- if标签:用于条件判断。
 
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}- for标签:用于循环遍历序列中的内容。
 
<ul>
{% for comment in comments %}
    <li>{{ comment.content }}</li>
{% endfor %}
</ul>- url标签:用于生成URL。
 
<a href="{% url 'my-view' %}">My View</a>- autoescape标签:用于控制是否开启或关闭自动转义。
 
{% autoescape off %}
    This will not be auto-escaped: {{ content }}.
{% endautoescape %}- block标签:用于在父模板中定义可以被子模板重写的区块。
 
{% block content %}
    <p>This is the default content.</p>
{% endblock %}- extends标签:用于继承父模板。
 
{% extends "base_generic.html" %}
{% block content %}
    <p>This is the child content.</p>
{% endblock %}- include标签:用于包含其他模板的内容。
 
{% include "footer.html" %}- comment标签:用于注释,不会显示在最终页面中。
 
{% comment %}
    This is a comment.
{% endcomment %}- cycle标签:用于在循环中交替使用一系列的值。
 
<tr class="{% cycle 'odd' 'even' %}">
...
</tr>- csrf\_token标签:用于生成CSRF令牌。
 
<form action="/login/" method="post">
    {% csrf_token %}
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" />
    <input type="submit" value="login" />
</form>- load标签:用于加载自定义的模板标签库。
 
{% load static %}- verbatim标签:用于防止模板引擎处理其中的内容。
 
{% verbatim %}
    This will not be processed by the template engine.
{% endverbatim %}- widthratio标签:用于根据一组数据计算宽度百分比。
 
{% widthratio this_value max_value max_width %}- static标签:用于生成静态文件的URL。
 
<img src="{% static "images/hi.jpg" %}" alt="Hi">- autoescape标签:用于控制是否对变量内容进行自动转义。
 
{{ body|safe }}以上是Django模板中常用的标签,每个标签都有其特定的用途和语法。在实际开发中,可以根据需要选择合适的标签来使用。
评论已关闭