Django module engine supports Django module language (DTL). DTL contains syntax such as variables, comments, filters, tags, module inheritance and HTML escape.
This paper introduces the following six module languages
1. Variable
2. Notes
3. Filter
4. Labels: include
5. Label: for
6. Label: in
1. Variable
DTL represents variables in the format of {{variable name}}. The variable name consists of letters, numbers and underscores, but cannot start with an underscore. When Django renders the template, the variables encountered are replaced with the corresponding variable values in the context. If the variable is an object, you can use the dot (·) to access its properties or methods.
2. Notes
DTL uses {#... #} to represent comments, and the contents of comments will not appear in the rendering results
The content annotated by {#... #} cannot wrap. To annotate multiline content, use the comment tag
<p>full name:{{ name }}</p> {% comment "multiline comment " %} <p>Age:{{ age }}</p> <p>Date:{{ now }}</p> {% endcomment %}
The age and date in the template are included in the annotation and are ignored when rendering. For example, use the sample code of the template in the view
def testTemplate(request): time=datetime.today() c={'name':"Small radium",'age':999,'now':time} return render(request,'testtem.html',c)
The rendering result displayed by the browser is shown in the figure below:
3. Filter
Filters are used to change the display results of variables. There are three commonly used filters:
(1) Default: sets the alternative value displayed when the variable is false or empty. The basic format is {{variable | default: alternative value}}
(2) Length: returns the length of a string or list. The basic format is {{variable | length}}
(3) Filesizeformat: converts numeric values to file size format, such as 1.1KB. The basic format is {{variable | filesizeformat}}
(Django provides more than 60 built-in module filters )
4. Labels: include
Tags are used to complete more complex operations, such as including modules, controlling processes, creating output text or implementing template inheritance.
The include tag is used to include modules, insert other template code into the current location, and render using the context of the current template.
The basic format of the include label is:
{% include module name%}
The module name can be a string or a string variable. For example, the template file testtemm.html code
Template A: {{data | default: 'nothing'}} < br >
Template file testtem1.html code
{%include 'testtemm.html'%}
Template B: current date: {% now "m / d / Y H:i:s"%}
The following tries to use the template testtem.html
def testTemplate1(request): return render(request,'testtem1.html',{'data':123})
The {% now%} tag is used in module testtem.html to obtain the current date string in the specified format. The browser displays the rendering result:
Parameters can be specified when the module is included,
{%include 'testtemm.html' with name='Small radium'%}
After with, the parameter is connected, and the parameter name is consistent with the variable name in the template. When passing multiple parameters, use spaces as separators
{%include 'testtemm.html' with data='abcd' data2=123%}
Example:
<!--chaper6\chaper6\templates\testtemm.html--> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> Template A: {%include 'testtem.html' with name='Small radium'%} </body> </html>
5. Label: for
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test1</title> </head> <body> <table> {% for r in data %} <tr> <td>The first{{forloop.counter}}that 's ok:</td> {% for a in r %} <td>{{a}}</td> {% endfor %} </tr> {% endfor %} </table> </body> </html>
The following attempts to use this template
def test1(request): data=[[1,2,3,4],[5,6,7,8],['a','b','c','d']] return render(request,'test1.html',{'data':data})
The rendering result displayed by the browser is shown in the figure below:
You can use reversed to indicate a reverse loop
{%for r in data reversed%}
After changing the for tag in the above template file test1.html to reverse loop, render the result (using the render result of reverse loop):
For a list variable that contains a sublist, the for tag maps the sublist to an independent variable,
<ul> {% for a,b,c,d in data %} <li> {{ a }},{{b}},{{ c }},{{ d }} </li> {% endfor %} </ul>
For dictionary objects, the for tag can map keys and values respectively. For example, dictionary objects {'name': "small radium" and 'age': 999} can use the following template:
<ul> {% for key,value in data.items %} <li> {{ key }}={{ value }} </li> {% endfor %} </ul>
The rendering result is shown in the figure below:
You can use {% empty%} inside the for tag block, which represents the output when the object to be traversed does not exist or is empty.
Example:
<ul> {% for key,value in data1.items %} <li> {{ key }}={{ value }} </li> {% empty %} The dictionary object was not found in the context, or data Empty {% endfor %} </ul>
Because data1 is an empty dictionary, {% empty%}
6. Label: if
The if tag is used to construct conditional branches. Its basic structure is as follows
{% if var1 %} .. {% elif var2 %} .. {% else %} .. {% endif %}
Elif and else blocks can be omitted, and there can be multiple elif blocks. Django calculates the variables of if and elif tags in sequence. If the variable is "true" (and the variable exists, is not empty, and is not False), the corresponding data block is output, and the process jumps to the endif tag. If no variable is "true", the else data block is output (if the else data block exists)
For example, the following modules output levels according to scores:
fraction:{{ data }}, {% if data >= 90 %} Grade: A {% elif data >= 80 %} Grade: B {% elif data >= 70 %} Grade: C {% elif data >= 60 %} Grade: D {% else %} Grade: unqualified {% endif %}
The following view uses this module:
def test2(request): data=int(request.GET['data']) return render(request,'test1.html',{'data':data})
This example obtains the score (formal format) from the URL, request. The data obtained by GET['data '] is in string format by default, so it needs to be converted to an integer. If it is not converted, Django will take it as a string, and the template will output the data of else tag.
Access in browser“ http://127.0.0.1:8000/test2?data=88 ”The output result is shown in the figure