Django template language
First of all a template is just a text file, it can generate any text-based format (HTML, XML, CSS, etc.), the template contains variables that are replaced with final values when the template is rendered, and tags that control the logic of the template.
Use {{ variable name}} for variables and {% tag%} for logical operations.
Simple basic template code:
{% extends "base_generic.html" %} {% block title %}{{ section.title }}{% endblock %} {% block content %} <h1>{{ section.title }}</h1> {% for story in story_list %} <h2> <a href="{{ story.get_absolute_url }}"> {{ story.headline|upper }} </a> </h2> <p>{{ story.tease|truncatewords:"100" }}</p> {% endfor %} {% endblock %}
1. Variables
Variables look like this: when the template engine encounters a variable, it is evaluated and replaced with the final value. Variable names consist of underscores, letters, and numbers. The dot (.) also appears in the variable section, but has a special meaning, use the dot (.) to access the properties of the variable.{{ variable}}
.。
When the template engine encounters a dot (.), it tries to find it in the following order:
dictionary key
property or method
numeric index
If the dot (.) is followed by a function name, it is called without arguments, and the parentheses are omitted, then the final result of the variable is the return value of the function.
It should be noted that if the key name in the dictionary is 'items', the value corresponding to the item in the dictionary will be obtained instead of calling the .items() method of the dictionary
Get the value of the variable demo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template language used</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> Single variable <span style= " color: red; " >{ { variable value} }</span> : {{ name }} </p> <hr> <p> List variables: {{ name_list }} <br> Lists can use the index to get the value name_list.0\name_list. 1: {{ name_list.0 }}<br> The list can use the index to get the value name_list. 0\name_list.1 : {{ name_list.1 }}<br> </p> <hr> <p> dictionary variables: {{ name_dict }} <br> dictionary variables are accessed via .key name_dict.first_name: {{ name_dict.first_name }} <br> dictionary variables are accessed via .key name_dict.last_name: {{ name_dict. last_name }} <br> Dictionaries are unordered and cannot be retrieved by index name_dict.0:{{ name_dict.0 }} <br> </p> <hr> <p> Pass an object p1:{{ p1 }} <br> Pass an object p2:{{ p2 }} <br> p1 name: {{ p1.name }},p1 age:{{ p1.age }} <br> p2 name: {{ p2.name }},p2 age:{{ p2.age }} <br> </p> <hr> <p> Object list method: obj_list.0 ->p1 obj_list.0.name/age: <br> p1 name: {{ obj_list.0.name }} <br> p1 age: {{ obj_list.0.age }} <br> </p> <hr style="color: red;"> </body> </html>
2. Label
The tag looks like this {% tag %}. First of all, tags are more complex than variables, some perform logical judgments, loop traversal, etc., and some load external information into templates for later variables to use. Some tags require start and end tags {% tag %} .... {% endtag %}. Django ships with about twenty built-in template tags. You can read all about them in the built-in tag reference . Only the commonly used tags are introduced here:
for
Loop through each item in the array. For example, to display the following provided list of athletes athlete_list
:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
for ... empty
The for tag takes an optional {% empty %} clause to operate if the given group is empty or not found.
<ul> {% for user in user_list %} <li>{{ user.name }}</li> {% empty %} <li>空空如也</li> {% endfor %} </ul>
if,else,elif
Evaluate a variable, and if the variable is "true", display the contents of the block:
{% 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 %}
Above, if athlete_list
not empty, the number of athletes will be displayed by the variable . Otherwise, if not empty, the "Athlete should be out..." message will be displayed. If both lists are empty, "no athletes". will be displayed.
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
with
Cache a complex variable with a simple name , useful when you need to use an "expensive" method (such as accessing a database) many times
{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %}
3. Filter
Use Filter to modify the displayed variables.
A filter looks like this: {value|filter:'...'}. value is the variable to modify, filter is the filter function, and the colon (:) is followed by the parameter. Django provides about 60 built-in template filters. You can read all about them in the built-in filter reference . To give you an idea of what's available, here are some of the more commonly used template filters:
defalue
If the variable is false or empty, the given default value is used. Otherwise, the value of the variable is used. E.g:
{{ value|default:"nothing" }}
If value
not provided or empty, " " will be displayed above nothing
.
length
The length of the return value. This works for strings and lists. E.g:
{{ value|length }}
If value is ['a','b','c','d'], the output will be 4.
filesizefamat
Formatted as a "human readable" file size value (ie , , etc.). E.g:'13 KB'
'4.1 MB'
'102 bytes'
{{ value|filesizeformat }}
-
If it
value
is 123456789, the output will be .117.7 MB
Again, these are just a few examples; see the built-in filters reference for the full list .
You can also create your own custom template filters;
4. Custom Filter
1. First, you need to create a templates directory (package) in the APP directory
requires attention:
After adding the templatetags module, you need to restart the server before you can use tags or filters in templates.
2. Create a py file containing custom tags and filters:
polls/ __init__.py models.py templatetags/ __init__.py poll_extras.py views.py
In your template, you can introduce custom tags and filters as follows:
{% load poll_extras %}
3. Import template
from django import template
4. Generate a registrar, which is an instance of template.Library()
register = template.Libraty()
5. Write a custom template filter
#Write a custom filter that does not accept parameters def add_a(arg1): return ' {}_a ' .format(arg1) #Write a custom filter that accepts parameters def add(arg1,arg2): return ' {}_{} ' .format(arg1,arg2) ''' arg1 : is a required parameter, the value to be modified before accepting the pipe character arg2 : is the parameter passed by the user, after the filter colon '''
6. Self-test custom filter
@register.filter(name= ' addA ' ) #register a custom filter def add_a(arg1): return ' {}_a ' .format(arg1) @register.filter(name = ' add ' ) #register a custom filter def add(arg1,arg2): return ' {}_{} ' .format(arg1,arg2)
7. Use custom filters
1. First import {% load myfilter%} in the page #Load the custom filter py file under the templates package {% load myfilter % } 2. Use {{ '123'|add_a }} The final result is: 123a {{ '123'|add:"abc" }} The final result is: 123abc
3. Need to restart the server
Five, simpletag
Similar to custom filter, but accepts more flexible parameters.
Define and register simple tag
@register.simple_tag(name="plus") def plus(a, b, c): return "{} + {} + {}".format(a, b, c)
Use custom simple tags
{% load app01_demo %} {# simple tag #} {% plus "1" "2" "abc" %}
Six, inclusion_tag returns an HTML fragment
Mostly used to return html code snippets
Example:
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>