Django 模板标签


模板标签

在 Django 模板中,您可以执行编程逻辑,例如执行if声明和for循环。

这些关键字,iffor,在 Django 中称为"template tags"。

为了执行模板标签,我们将它们包围在{% %}括号。

示例

templates/template.html:

{% if greeting == 1 %}
  <h1>Hello</h1>
{% else %}
  <h1>Bye</h1>
{% endif %}
运行示例 »

Django代码

模板标签是告诉 Django 这里有一些不同于纯 HTML 的东西的一种方式。

模板标签允许我们在将 HTML 发送到客户端之前在服务器上进行一些编程。

templates/template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>
运行示例 »

在接下来的章节中,您将了解最常见的模板标签。


标签参考

所有模板标签的列表:

Tag Description
autoescape Specifies if autoescape mode is on or off
block Specifies a block section
comment Specifies a comment section
csrf_token Protects forms from Cross Site Request Forgeries
cycle Specifies content to use in each cycle of a loop
debug Specifies debugging information
extends Specifies a parent template
filter Filters content before returning it
firstof Returns the first not empty variable
for Specifies a for loop
if Specifies a if statement
ifchanged Used in for loops. Outputs a block only if a value has changed since the last iteration
include Specifies included content/template
load Loads template tags from another library
lorem Outputs random text
now Outputs the current date/time
regroup Sorts an object by a group
resetcycle Used in cycles. Resets the cycle
spaceless Removes whitespace between HTML tags
templatetag Outputs a specified template tag
url Returns the absolute URL part of a URL
verbatim Specifies contents that should not be rendered by the template engine
widthratio Calculates a width value based on the ratio between a given value and a max value
with Specifies a variable to use in the block