在django中,模板实际上就是静态文本文件,包括HTML、XML、CSV等。Django中的模板语言主要包含变量(Variables)和关键字(Tags)两部分。变量用{{values}}表示,语句用{% %}表示。
相关链接
字典操作
{% for k, v in defaultdict.items %}
Do something with k and v here...
{% endfor %}
变量操作
default
{{ value|default:"nothing" }}
# If value isn’t provided or is empty, the above will display “nothing”.
length
{{ value|length }}
# If value is ['a', 'b', 'c', 'd'], the output will be 4.
filesizeformat
{{ value|filesizeformat }}
#If value is 123456789, the output would be 117.7 MB.
#123456789,代表123456789字节
关键字Tags
for
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
if, elif, and else
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
block和extends
block标签,作用于该块
extends标签,将外界html文件导入。并用当前模板相同快名称的内容去代替父模板中相同块的内容。
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}