1.0 GENERAL grammar
Only need to remember two special symbols:
{{ }}with {% %}
Variable associated with {{}}, {logic associated with %%}.
1.1 Variable
Click Django template language syntax used in: {{name}} variable.
When the template engine encounters a variable, it will calculate the variable, and then replace it with the result itself. Named variables include any alphanumeric and underscore ( "_") combination. Variable names can not contain spaces or punctuation.
Dot (.) Has a special meaning in the template language. When the template system encounters a dot ( "."), It will be in this order inquiries:
Dictionary lookup (Dictionary lookup)
property or method query (Attribute or method lookup)
digital index query (Numeric index lookup)
Precautions:
- If the value of calculation result is called, it will be invoked with no parameters. Result of the call will be the value of the template.
- If variables does not exist, the system will insert the value string_if_invalid template option, which is the default setting is '' (the empty string).
A few examples:
view code:
def template_test(request): l = [11, 22, 33] d = {"name": "alex"} class Person(object): def __init__(self, name, age): self.name = name self.age = age def dream(self): return "{} is dream...".format(self.name) Alex = Person(name="Alex", age=34) Egon = Person(name="Egon", age=9000) Eva_J = Person(name="Eva_J", age=18) person_list = [Alex, Egon, Eva_J] return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list})
Template support wording:
{ # Take the first parameter l} # {l.0} {} { # take the dictionary key value} # {d.name} {} { # take the object name attribute} # {{person_list.0 }} .name { # . # operation method can only be called with no arguments} {} {} person_list.0.dream
1.2 Filters Filters
In Django template language by using filters to change the display of variables.
The syntax of the filter: {{value | filter_name: Parameter}}
Use pipe symbol "|" applying a filter.
For example: {{name | lower}} then the variable name will show its value after the application of lower filter. lower in action here is all lowercase text.
Precautions:
- Filter supports the "chain" operation. I.e., a filter output as input to another filter.
- Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
- Filter parameter contains a space, it must be wrapped in quotes. Such as comma and a space used to connect the elements of a list, such as: {{list | join: ','}}
- '|' Around is no space without a space with no spaces
Django template language provides about sixty built-in filter.
default
If a variable is false or empty, the default values given. Otherwise, use the value of the variable.
{{ value|default:"nothing"}}
If value is null or the value is not passed, then nothing is displayed
length
Returns the length, acting on the string and the value list.
{{ value|length }}
filesizeformat
Value formatted as a "human readable" file size (e.g. '13 KB'
, '4.1 MB'
, '102 bytes'
, etc.). E.g
{{ value|filesizeformat }}
slice
slice
{{value|slice:"2:-1"}}
date
format
{{ value|date:"Y-m-d H:i:s"}}
Available parameters:
Formatting characters | description | Sample output |
---|---|---|
a | 'a.m.' Or 'p.m.' (Note that this is slightly different with PHP's output, because this includes the period in line with Associated Press style) |
'a.m.' |
A | 'AM' Or 'PM' . |
'AM' |
b | Month, word, three letters, lowercase. | 'jan' |
B | Unrealized. | |
c | ISO 8601 format. (Note: Unlike other formatting procedures, for example, "Z", "O" or "r", if the value naive datetime, the "c" format program does not add time zone offset |
2008-01-02T10:30:00.000123+02:00 Or 2008-01-02T10:30:00.000123 if naive datetime |
d | May the day with 2 digits with leading zeros. | '01' To'31' |
D | Word of the week, three letters. | “星期五” |
e | Time zone name may be in any format, or may return a null string, depending datetime. | '' , 'GMT' , '-500' , 'US/Eastern' Etc. |
E | Month, instead of specific regions commonly used to represent long date representation. | 'listopada' (For Polish regions, not 'Listopad' ) |
f | Time, within 12 hours hours and minutes, if they are zero, the minute hold. Proprietary extensions. | '1' ,'1:30' |
F | Month, text, long. | '一月' |
g | Hour, 12-hour format, without leading zeros. | '1' To'12' |
G | Hour, 24-hour format, without leading zeros. | '0' To'23' |
h | Hour, 12-hour format. | '01' To'12' |
H | Hour, 24-hour format. | '00' To'23' |
i | minute. | '00' To'59' |
I | Daylight Saving Time, regardless of whether or not to take effect. | '1' or'0' |
j | No day leading zeros of the month. | '1' To'31' |
l | Day of the week, word length. | '星期五' |
L | Whether the Boolean value is a leap year. | True orFalse |
m | Month, 2 digits with leading zeros. | '01' To'12' |
M | Month, word, three letters. | “扬” |
n | Months No leading zeros. | '1' To'12' |
N | Associated Press style abbreviation for the month. Proprietary extensions. | 'Jan.' ,'Feb.' ,'March' ,'May' |
O | ISO-8601 week number corresponding to the number of weeks using the leap (W) ISO-8601. For the more common year format, see Y. | '1999年' |
O | Greenwich Mean Time difference within a few hours. | '+0200' |
P | For 12 hours, minutes and 'am. '/' pm. ', If the zero minute hold, in special circumstances the string "midnight" and the "noon." Proprietary extensions. | '1 am' ,'1:30 pm' / t3>, |
r | Formatting date. | 'Thu, 21 Dec 2000 16:01:07 +0200' |
s | Seconds, 2 digits with leading zeros. | '00' To'59' |
S | English ordinal suffix month, two characters. | 'st' , 'nd' , 'rd' Or'th' |
t | To the number of days in a given month. | 28 to 31 |
T | Time zone of the machine. | 'EST' ,'MDT' |
in | Microseconds. | 000000 to 999999 |
The | Since one-half the Unix Epoch (January 1 1970 00:00:00 UTC). | |
w | Day of the week, digits without leading zeroes. | '0' (Sunday) to '6' (Saturday) |
W | ISO-8601 a few weeks, weeks starting on Monday. | 1 ,53 |
Y | Year, 2 digits. | '99' |
Y | Year 4 digits. | '1999年' |
with | Day of the year | 0 To365 |
WITH | Time zone offset, in seconds. Time zone UTC offset is always a negative west, east to UTC time, they are always positive. | -43200 To43200 |
safe
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。
比如:
value = "<a href='#'>点我</a>"
{{ value|safe}}
truncatechars
如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。
参数:截断的字符数
{{ value|truncatechars:9}}
truncatewords
在一定数量的字后截断字符串。
{{ value|truncatewords:9}}
cut
移除value中所有的与给出的变量相同的字符串
{{ value|cut:' ' }}
join
使用字符串连接列表,例如Python的str.join(list)
timesince
将日期格式设为自该日期起的时间(例如,“4天,6小时”)。
采用一个可选参数,它是一个包含用作比较点的日期的变量(不带参数,比较点为现在)。 例如,如果blog_date是表示2006年6月1日午夜的日期实例,并且comment_date是2006年6月1日08:00的日期实例,则以下将返回“8小时”:
{{ blog_date|timesince:comment_date }}
分钟是所使用的最小单位,对于相对于比较点的未来的任何日期,将返回“0分钟”。
timeuntil
似于timesince,除了它测量从现在开始直到给定日期或日期时间的时间。 例如,如果今天是2006年6月1日,而conference_date是保留2006年6月29日的日期实例,则{{ conference_date | timeuntil }}将返回“4周”。
使用可选参数,它是一个包含用作比较点的日期(而不是现在)的变量。 如果from_date包含2006年6月22日,则以下内容将返回“1周”:
{{ conference_date|timeuntil:from_date }}
自定义filter
自定义过滤器只是带有一个或两个参数的Python函数:
- 变量(输入)的值 - -不一定是一个字符串
- 参数的值 - 这可以有一个默认值,或完全省略
例如,在过滤器{{var | foo:'bar'}}中,过滤器foo将传递变量var和参数“bar”。
自定义filter代码文件摆放位置:
app01/ __init__.py models.py templatetags/ # 在app01下面新建一个package package __init__.py app01_filters.py # 建一个存放自定义filter的文件 views.py
编写自定义filter
from django import template register = template.Library() @register.filter(name="cut") def cut(value, arg): return value.replace(arg, "") @register.filter(name="addSB") def add_sb(value): return "{} SB".format(value)
使用自定义filter
{# 先导入我们自定义filter那个文件 #}
{% load app01_filters %}
{# 使用我们自定义的filter #}
{{ somevariable|cut:"0" }}
{{ d.name|addSB }}
1.3 Tags
for循环
普通for循环
<ul> {% for user in user_list %} <li>{{ user.name }}</li> {% endfor %} </ul>
for循环可用的一些参数:
Variable | Description |
---|---|
forloop.counter |
当前循环的索引值(从1开始) |
forloop.counter0 |
当前循环的索引值(从0开始) |
forloop.revcounter |
当前循环的倒序索引值(从1开始) |
forloop.revcounter0 |
当前循环的倒序索引值(从0开始) |
forloop.first |
当前循环是不是第一次循环(布尔值) |
forloop.last |
当前循环是不是最后一次循环(布尔值) |
forloop.parentloop |
本层循环的外层循环 |
for ... empty
<ul> {% for user in user_list %} <li>{{ user.name }}</li> {% empty %} <li>空空如也</li> {% endfor %} </ul>
if判断
if,elif和
else
{% if user_list %}
用户人数:{{ user_list|length }}
{% elif black_list %}
黑名单数:{{ black_list|length }}
{% else %}
没有用户
{% endif %}
当然也可以只有if和else
{% if user_list|length > 5 %}
七座豪华SUV
{% else %}
黄包车
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
with
定义一个中间变量,多用于给一个复杂的变量起别名。
注意等号左右不要加空格。
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
csrf_token
这个标签用于跨站请求伪造保护。
在页面的form表单里面写上{% csrf_token %}
注释
{# ... #}
1.4 母版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> {% block page-css %} {% endblock %} </head> <body> <h1>这是母板的标题</h1> {% block page-main %} {% endblock %} <h1>母板底部内容</h1> {% block page-js %} {% endblock %} </body> </html>
1.5 继承母版
在子页面中在页面最上方使用下面的语法来继承母板。
{% extends 'layouts.html' %}
1.6 块(block)
通过在母板中使用{% block xxx %}
来定义"块"。
在子页面中通过定义母板中的block名来对应替换母板中相应的内容。
{% block page-main %} <p>世情薄</p> <p>人情恶</p> <p>雨送黄昏花易落</p> {% endblock %}
1.7 组件
可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可。
{% include 'navbar.html' %}
1.8 静态文件相关
{% static %}
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
引用JS文件时使用:
{% load static %} <script src="{% static "mytest.js" %}"></script>
某个文件多处被用到可以存为一个变量
{% load static %} {% static "images/hi.jpg" as myphoto %} <img src="{{ myphoto }}"></img>
{% get_static_prefix %}
{% load static %} <img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />
1.9 simple_tag
和自定义filter类似,只不过接收更灵活的参数。
定义注册simple_tag
@register.simple_tag(name="plus") def plus(a, b, c): return "{} + {} + {}".format(a, b, c)
使用自定义simple_tag
{% load app01_demo %}
{# simple tag #}
{% plus "1" "2" "abc" %}
1.10 inclusion_tag
多用于返回html代码片段
示例:
templatetags/my_inclusion.py
from django import template register = template.Library() @register.inclusion_tag('result.html') def show_results(n): n = 1 if n < 1 else int(n) data = ["第{}项".format(i) for i in range(1, n+1)] return {"data": data}
templates/snippets/result.html
<ul> {% for choice in data %} <li>{{ choice }}</li> {% endfor %} </ul>
templates/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>inclusion_tag test</title> </head> <body> {% load inclusion_tag_test %} {% show_results 10 %} </body> </html>