Django 基础教程

Django 查询

Django 展示数据

Django Admin

Django 模板

Django 表单组件

Django 高级

Django FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/django-template-tag.html

django template 模板支持的所有标签语法详解


Django 中的模板标签是在模板中使用的特殊标记,用于控制模板渲染过程。这些标签使用 {% %} 语法,让你能够在模板中执行逻辑、循环、条件语句等操作。下面列出一些常用的 Django 模板标签,并附上详细的代码示例介绍它们的作用和使用方法:

if标签

if 标签:用于条件判断。

{% if condition %}
    {# 如果条件成立时执行的内容 #}
{% else %}
    {# 如果条件不成立时执行的内容 #}
{% endif %}

示例:

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in to continue.</p>
{% endif %}

for标签

for 标签:用于循环迭代。

{% for item in items %}
    {# 在每次循环迭代时执行的内容 #}
{% empty %}
    {# 当列表为空时执行的内容 #}
{% endfor %}

示例:

<ul>
    {% for product in products %}
        <li>{{ product.name }} - ${{ product.price }}</li>
    {% empty %}
        <li>No products available.</li>
    {% endfor %}
</ul>

block标签

block 标签:用于定义可被覆盖的块,通常与继承模板一起使用。

{% block block_name %}
    {# 块的内容 #}
{% endblock %}

示例:

{% block content %}
    <h1>Welcome to our website!</h1>
{% endblock %}

extends标签

extends 标签:用于继承其他模板。

{% extends "base_template.html" %}

示例:

base_template.html:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

home.html:

{% extends "base_template.html" %}
{% block title %}Home{% endblock %}

{% block content %}
    <h1>Welcome to our website!</h1>
{% endblock %}

include标签

include 标签:用于包含其他模板。

{% include "partial_template.html" %}

示例:

partial_template.html:

<div>
    <p>This is a partial template.</p>
</div>

main_template.html:

<!DOCTYPE html>
<html>
<head>
    <title>Main Template</title>
</head>
<body>
    {% include "partial_template.html" %}
</body>
</html>

with标签

with 标签:用于为变量赋值,以便在模板中重复使用。

{% with variable=value %}
    {# 使用变量 #}
{% endwith %}

示例:

{% with username=user.username %}
    <p>Welcome, {{ username }}!</p>
{% endwith %}

url标签

url 标签:用于生成 URL。

{% url 'url_name' arg1 arg2 %}

示例:

{% url 'product_detail' product.id %}

csrf标签

csrf 标签:用于生成 CSRF 令牌,防止跨站请求伪造。

{% csrf_token %}

示例:

<form method="post">
    {% csrf_token %}
    {# 表单内容 #}
</form>