This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Basic Django template syntax
The Django template system involves template variables, filters, template tags, and more.
-
The template variable is {{name}}, {{}} is a variable name
-
Filters are used to deal with template variables, such as changing the display
-
Template tags look like {% name%}, {%%} is a logical name
Template file
Template files in Django are HTML files
Normally we will create a folder called templates under the project root (where the manage.py file is located) to store our template files.
The DIRS is where the template file path is set in the TEMPLATES block of the settings.py file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates'.Define a list of directories in which the template engine looks for template files in sequence
'DIRS': [os.path.join(BASE_DIR, 'templates')].# APPS_DIRS = True
'APP_DIRS': True.'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug'.'django.template.context_processors.request'.'django.contrib.auth.context_processors.auth'.'django.contrib.messages.context_processors.messages',],},},]Copy the code
Template variables
The template variable is in the format of {{name}}, where name indicates the variable name, and there must be a space on both sides of the name. The variable name can contain letters, digits, and underscores, but cannot contain Spaces or punctuation marks.
Template variables are embedded in HTML files, and when the Django template engine detects a template variable, it replaces it with the actual value or content that the variable represents.
In the template variable, add a dot after the variable name. Added as a string, the Django template engine will parse the variable depending on the situation. If it is a dictionary variable, the key value is queried in the dictionary format. If it is a class object variable, it is queried by property or method; If it is a list variable, query by index number.
Example:
view
def test(request) :
a='test'
b={'n':'Test dictionary'}
return render(request,'test.html', {'a':a,'b':b})
Copy the code
html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ a }}</h1>
<h1>{{ b.n }}</h1>
</body>
</html>
Copy the code
Template annotation
Comments can also be used in template languages, such as {# ××× #}
The single-line comment looks like this. {#}Multi-line comments use comment tags. {% comment %} ........ {% endcomment %}Copy the code
The filter
Reprocessing template variables through filters changes the form or content of template variables
{{name | filter_name: parameter}}Copy the code
The pipe “|” is on the right side of the filter name
Filters can pass parameters. Filter names and parameters are separated by colons (:)
The filter format, the pipe “|” and “:” in front of the back of the parameter will be as a parameter to filter processing
Built-in filter
Common filter
-
Filter, the default format for {{name | default: “default”}}, if the value of the template variable is empty or False, it shows the default values.
-
Filter length, format for {{name | length}}, show the length of the template variables.
-
Filter truncatechars, format for {{name | truncatechars: 6}}, apply to a template variable string is the case, according to the specified number of characters, the back with an ellipsis “…” At the end, “…” Counts as three characters. For example, if the input parameter contains six characters, enter three characters from the string and add… .
-
Upper and lower filter, {{name | upper}} converts a string to all uppercase form; {{name | lower}} all converts a string to lowercase.
-
Filter slice, format for {{name | slice: “:” 2}}, used in the template variable list or a string is the case, according to one part of it, which is sliced, the same as the Python slice syntax.
-
Filter, the date format for {{name | date: “Y -m – d H: I: s”}}, used in the template variable is the date or time, provide formatted output.
-
Filter safe, format for {{name | safe}}, for the sake of safety, Django template will be the HTML tags and the syntax of Java Script code labels automatically escape (into plain text string), a filter safe will shut down automatically escape function
Example:
view
def test(request) :
a='test'
b='<h1>123<h1>'
c='abcABC'
time=datetime.datetime.now()
return render(request,'test.html', {'a':a,'b':b,'c':c,'time':time})
Copy the code
html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<H1>{{ c|length }}</H1>
<H1>{{ c|truncatechars:2 }}</H1>
<H1>{{ c|upper }}</H1>
<H1>{{ c|lower }}</H1>
<H1>{{ c|slice:"2:5" }}</H1>
<H1>{{ c|date:"Y-m-d H:i:s" }}</H1>
<H1>{{ b }}</H1>
<H1>{{ b|safe}}</H1>
</body>
</html>
Copy the code
Template tags
Built-in template tag
Template tag if
For judgment purposes, although it is in an HTML file, its syntax is very similar to Python code syntax. If {% if %} is true, the template system displays the content between {% if %} and {% endif %}. The template tag if can contain {% else %}, {% elif %} clauses.
{% if a>0 %}
a>0
{% elif a<0 %}
a<0
{% else %}
a=0
{% endif %}
Copy the code
Template tags ifequal and IfNotequal
One is used to determine whether two values are equal, and one is used to determine whether two values are not equal.
{% ifequal a 0 %}
a=0
{% endifequal %}
{% ifnotequal a 0%} a! =0
{% endifnotequal %}
Copy the code
For loop template tag
Similar to Python code syntax, {% for %} is used to loop over iterable variables, displaying the contents between {% for %} and {% endfor %} each time through the loop.
{% empty %} # Check whether the list is empty
Let’s say a list variable lists
lists=[{'naem':1}, {'naem':2}, {'naem':3}, {'naem':4},]
Copy the code
{% for user in lists%} {{user.name}} {% empty %} # Check whether the list is empty {% endfor %}Copy the code
Built-in argument for the for loop tag
Low forloop. Counter: from1Begins to return the index value of the current loop. Low forloop. Counter0: from0Begins to return the index value of the current loop. ●forloop. revCounter: Returns the index value of the current loop in reverse order, starting with the maximum index value and ending with the value1. ●forloop. revCounter0: Returns the index value of the current loop in reverse order, starting with the maximum index value and ending with the value0. ●forloop.first: Returns a Boolean value indicating whether the current loop is the first. ●forloop.last: Returns a Boolean value indicating whether the current loop was the last. ●forloop.parentloop: the outer loop (parentloop) of this layer.Copy the code
Example:
{% for user inLists %} {{forloop.counter}} the name is: {{user.name}} {% empty %}Check if the list is emptyNo data {% endfor %}Copy the code