Django Template System
Official document: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std: Templatetag-for
Common syntax
Only two special symbols need to be recorded:
{{}} and {%}
Variables related to {{}}, logically related with {percent}.
Variable
{{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.
A few examples:
View in code:
def template_test (Request): L = [one, all,] 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})
Supported notation in templates:
{# takes the first parameter in L #} {{l.0}} {# takes the value of key in the dictionary #} {{D.name}} {# Fetch the object's Name property #} {{Person_list.0.name}} {#. Operation can only invoke a method without parameters #} {{Person_list.0.dream}}
Filters
Syntax: {{value|filter_name: parameter}}
Default
{{value|default: "Nothing"}}
Show nothing if value is not passed
Length
{{Value|length}}
| No space around no space no spaces
Returns the length of value, such as value=[' A ', ' B ', ' C ', ' d '], which shows 4.
Filesizeformat
Format the value as a "human-readable" file size (for example,, ‘13 KB‘
‘4.1 MB‘
, and ‘102 bytes‘
so on). For example:
{{Value|filesizeformat}}
If value is 123456789, the output will be 117.7 MB.
Slice
Slice
{{value|slice: ' 2:-1 '}}
Date
Formatting
{{value|date: "Y-m-d h:i:s"}}
Safe
The Django template automatically escapes syntax tags such as HTML tags and js, for obvious reasons, for security. But sometimes we may not want these HTML elements to be escaped, such as we do a content management system, the background is added to the article is decorated, these decorations may be a similar to the FCKeditor editor to fill the HTML modifier text, If auto-escaping, the source file that protects the HTML tag is displayed. There are two ways to turn off automatic HTML escaping in Django, and if it's a separate variable, we can tell Django that this code is safe without escaping with the filter "|safe".
Like what:
Value = "<a href= ' # ' > Dot me </a>"
{{Value|safe}}
Truncatechars
If the string character is more than the specified number of characters, it is truncated. The truncated string ends with a translatable sequence 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-this 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__.py models.py templatetags/ # Create a new package package APP01 below __init__.py app01_filters.py # Build a file to store your custom filter views.py
Writing a custom filter
From 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
{# Pilot into our custom filter file #} {% load app01_filters%} {# using our custom filter #} {{somevariable|cut: ' 0 '}} {{D.NAME|ADDSB}}
Tags
For
<ul>{% for user in user_list%} <li>{{user.name}}</li>{% endfor%}</ul>
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 |
Reverse index value of the current loop (starting at 1) |
forloop.revcounter0 |
Reverse index value of the current loop (starting at 0) |
forloop.first |
The current loop is not the first loop (Boolean value) |
forloop.last |
The current loop is not the last loop (Boolean value) |
forloop.parentloop |
Outer loop of this layer loop |
For ... empty
<ul>{% for user in user_list%} <li>{{user.name}}</li>{% empty%} <li> empty </li> {% ENDfor%}</ul>
if,elif和
else
{% if user_list%} Number of users: {{user_list|length}}{% elif black_list%} blacklist: {{black_list|length}}{% else%} no user {% endif%}
Of course, you can have only if and else
{% if user_list|length > 5} Seven seater deluxe suv{% else%} Rickshaw {% endif%}
The IF statement supports and, or, = =, >, <,! =, <=, >=, in, not-in, is, is-not judgment.
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
1. The Django template language does not support continuous judgment, that is, the following notation is not supported:
{% If a > B > C%} ... {% ENDIF%}
2. The precedence of attributes in the Django template language is greater than the method
def xx (request): D = {"A": 1, "B": 2, "C": 3, "items": "+"} 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 in the template language:
{{Data.items}}
The value of the items key for D is taken by default.
Master Board
<! 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.
Inherit the master boardIn the sub-page, use the following syntax at the top of the page to inherit the motherboard.
{% extends ' layouts.html '%}
Blocks (block)Define "blocks" by using them in the master board {% block xxx %}
.
Replace the corresponding contents in the motherboard by defining the block name in the master board in the sub-page.
{% block Page-main%} <p> Thin </p> <p> human evil </p> <p> rain Send dusk flower </p>{% endblock%}
ComponentYou 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%}
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{% load static%}
Or
{% load static%} {% Get_static_prefix as Static_prefix%}
Custom Simpletagis similar to a custom filter, except that it receives more flexible parameters.
Define register Simple Tag
@register. Simple_tag (name= "plus") def plus (A, B, c): return "{} + {} + {}". Format (A, B, c)
Use the custom simple tag
{% load App01_demo%} {# simple Tag #} {% plus "1" "2" "ABC"%}
Inclusion_tagMore for returning 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 = ["{} key". 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-related content