Common syntax for Django template language
Only two special symbols need to be recorded:
{{ }}
And{% %}
Variables related to the use of {{}}
logic-related{% %}
Variable
{{ name }} --->变量
Variable names consist of alphanumeric characters and underscores.
The point (.) has a special meaning in the template language, which is used to get the corresponding property values of the object.
Example:
The code in view:
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})
The notation supported in the template:
{# 取l中的第一个参数 #}{{ l.0 }}{# 取字典中key的值 #}{{ d.name }}{# 取对象的name属性 #}{{ person_list.0.name }}{# .操作只能调用不带参数的方法 #}{{ person_list.0.dream }}
Filters
Syntax: {{value|filter_name: parameter}}
Default
{{ value|default:‘nothing‘ }}
Show nothing if value is not passed
Length
{{Value|length}}
|左右不能有空格|左右不能有空格|左右不能有空格
Returns the length of value, such as value=[' a ', ' B ', ' C ', ' d ', which shows 4.
Filesizeformat
Format values as a readable file size
{{ value|filesizeformat }}
If value is 123456789, the output will be 117.7MB
Slice
Slice
{{ value|slice:‘2:-1‘ }}
Date
Formatting
{{ value|date:‘Y-m-d H:i:s‘ }}
Safe
For security purposes, the Django template automatically escapes syntax tags such as HTML tags and js. You can use the filter ' |safe ' to let Django not escape
Example:
value = "<a href='#'>点我</a>"{{ value|safe }}
Truncatechars
If the string character is more than the number of characters set, it is truncated. The truncated string ends with a translatable series of ellipses (' ... ').
Parameters: Number of characters truncated
{{ value|truncatechars:9 }}
Custom Filter
The custom filter is just a Python function with one or two parameters:
- The value of the variable (input)--not necessarily a string
The value of the parameter-can have a default value, or completely omit
For example, in the filter {{var|foo: ' Bar '}}, the filter foo will pass the variable var and the parameter ' bar '
Custom filter code file placement:
app01/__init__.pymodels.pytemplatetags/ # 在app01下面新建一个package package,文件名必须是templatetags __init__.py app01_filters.py # 建一个存放自定义filter的文件views.py
Writing a custom filter
rom django import templateregister = 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)
Using a custom filter
{# 先导入我们自定义filter那个文件 #}{% load app01_filters %}{# 使用我们自定义的filter #}{{ somevariable|cut:"0" }}{{ d.name|addSB }}
Tags
For
{% for x in list %}{% endfor %}
Some parameters available for the For loop:
| variable| description|
|--|--|
|forloop.counter| index value of the current loop (starting at 1) |
|forloop.counter0| index value of the current loop (starting at 0) |
|forloop.revcounter| the reverse index value of the current loop (starting at 1) |
|forloop.revcounter0| the reverse index value of the current loop (starting at 0) |
|forloop.first| The current loop is not the first loop (Boolean) |
|forloop.last| The current loop is not the last loop (Boolean) |
|forloop.parebtloop| the outer loop of this layer loop |
For...empty
When the sequence for the For loop is empty, execute empty
<ul>{% for user in user_list %} <li>{{ user.name }}</li>{% empty %} <li>空空如也</li>{% endfor %}</ul>
If,elif,else
{% if user_list %} 用户人数:{{ user_list|length }}{% elif black_list %} 黑名单数:{{ black_list|length }}{% else %} 没有用户{% endif %}
Of course, you can have only if and else
{% if user_list|length > 5 %} 七座豪华SUV{% else %} 黄包车{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
With
Define an intermediate variable
{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }}{% endwith %}
Csrf_token
This tag is used for cross-site request forgery protection
Write {% Csrf_token%} in the form form on the page
Comments
{# ... #}
Precautions
The 1.Django template language does not support continuous judgment, that is, the following notation is not supported:
{% if a>b>c %}{%endif%}
The precedence of attributes in the 2.Django template language is greater than the method
def xx(request): d = {"a": 1, "b": 2, "c": 3, "items": "100"} return render(request, "xx.html", {"data": d})
As above, when we render a page using the Render method, the dictionary D has a key that is items and has the default D.items () method, which is in the template language:
{{ data.items }}
The value of the items key for D is taken by default.
Master version
Place the same parts of multiple pages in a single file,
These same parts can be inherited by specific symbols.
<!DOCTYPE html>
Note: We usually define the CSS blocks and JS blocks for the page in the motherboard, which is convenient for the sub-page substitution.
Blocks (block)Define blocks by using {% block xxx%} in the Master
Replace the corresponding content in the master by defining the block name in the master in the child page
{% block page-main %} <p>世情薄</p> <p>人情恶</p> <p>雨送黄昏花易落</p>{% endblock %}
Inherit MasterUse the following syntax to inherit the master at the top of the sub-page
{% extends 'layouts.html' %}
Component
You can save commonly used page content such as navigation bar, footer information and other components in a separate file, and then in the place you need to use the following syntax to import.
{% include ‘navbar.html‘ %}
Static file-related{% load static %}
The path of the auto-stitching static file. The correct path can be obtained regardless of how the configuration in the setting file is /static/
changed.
{% load static %}
When referencing a JS file, use:
{% load static %}<script src="{% static "mytest.js" %}"></script>
A file is used in many places to be saved as a variable
{% load static %}{% static "images/hi.jpg" as myphoto %}</img>
Using Get_static_prefix (Manually stitching a static file path){% load static %}
Or
{% load static %}{% get_static_prefix as STATIC_PREFIX %}
Custom Simple_tag
Similar to custom filter, but accepts more flexible parameters
Define Registration Simple_tag
@register.simple_tag(name="plus")def plus(a, b, c): return "{} + {} + {}".format(a, b, c)
Using a custom Simpletag
{% load app01_demo %}{# simple tag #}{% plus "1" "2" "abc" %}
Inclusion_tag
Used to return HTML code snippets
Example:
templatetags/my_inclusion.py
from django import templateregister = 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>
Django Template language