SoFunction
Updated on 2024-12-16

Django framework template usage

existPrevious chapterIn this case we use () to output "Hello World!". This approach mixes data with views and is not in line with Django's MVC philosophy.

In this section we will give you a detailed introduction to the use of Django templates, which is a text that is used to separate the presentation and content of a document.

I. Examples of template applications

Let's move on.Previous chapterThe project will create the templates directory under the HelloWorld directory and create the files, the entire directory structure is as follows:

HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- 
|   |-- 
|   |-- 
|   |-- 
|   |-- 
|   |-- 
|   |-- 
|   `-- 
|-- 
`-- templates
    `-- 

The file code is as follows:

<h1>{{ hello }}</h1>

We know from the template that variables use double brackets.

Next we need to indicate to Django the path to the template file, change HelloWorld/, change DIRS in TEMPLATES to [BASE_DIR+"/templates",] as follows.

...TEMPLATES = [
    {
        'BACKEND': '',
        'DIRS': [BASE_DIR+"/templates",],       # Modify location
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                '.context_processors.debug',
                '.context_processors.request',
                '.context_processors.auth',
                '.context_processors.messages',
            ],
        },
    },
]
...

We now modify , adding a new object for submitting data to the template:

from  import render
 
def runoob(request):
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, '', context)

File Code:

from  import path
 
from . import views
 
urlpatterns = [
    path('runoob/', ),
]

As you can see, we're using render instead of HttpResponse, and render also takes a dictionary context as a parameter.

context The key value of the element in the dictionaryhello corresponds to the variable {{ hello }} in the template.

Re-visithttp://127.0.0.1:8000/runoob, you can see the page:

This completes our use of templates to output data, thus separating the data from the view.

Next we will specifically cover the syntax rules commonly used in templates.

Second, Django template tags

1. Variables

Template syntax:

view:{"HTML variable name" : "Views variable name"}
HTML:{{variable name}}
from  import render

def runoob(request):
  views_name = ""
  return  render(request,"", {"name":views_name})

templates in :

<p>{{ name }}</p>

Visit http://127.0.0.1:8000/runoob again to see the page:

2. List

In templates, the corresponding element can be retrieved with the . index subscript to retrieve the corresponding element.

HelloWorld/HelloWorld/ file code:

from  import render

def runoob(request):
    views_list = ["1","2","3"]
    return render(request, "", {"views_list": views_list})

HelloWorld/templates/ file code:

<p>{{ views_list }}</p>   # Fetch the entire list
<p>{{ views_list.0 }}</p> # Remove the first element of the list

Visit http://127.0.0.1:8000/runoob again to see the page:

3. Dictionary

In templates, the corresponding value can be retrieved with the . key to retrieve the corresponding value.

HelloWorld/HelloWorld/ file code:

from  import render

def runoob(request):
    views_dict = {"name":""}
    return render(request, "", {"views_dict": views_dict})

HelloWorld/templates/ file code:

<p>{{ views_dict }}</p>
<p>{{ views_dict.name }}</p>

Visit http://127.0.0.1:8000/runoob again to see the page:

4. Filter

Template syntax:

{{ variable name | (machine) filter:Optional parameters }}

Template filters can modify a variable before it is displayed, and the filters use pipe characters, as shown below:

{{ name|lower }}

The {{ name }} variable is processed by the filter lower, which converts document upper case to lower case.

Filter pipes can be * socketed*, meaning that the output of one filter pipe can in turn be used as the input of the next pipe:

{{ my_list|first|upper }}

The above example takes the first element and converts it to uppercase.

Some filters have parameters. Filter parameters follow a colon and are always enclosed in double quotes. For example:

{{ bio|truncatewords:"30" }}

This will display the first 30 words of the variable bio.

Other filters:

  • addslashes : Adds backslashes in front of any backslash, single or double quote.
  • date : Formats a date or datetime object according to the specified format string argument, instance:
{{ pub_date|date:"F j, Y" }}
  • length : Returns the length of the variable.

(1)default

default Provides a default value for the variable.

If the boolean value of the variable passed by views is false, the specified default value is used.

The following values are false:

0  0.0  False  0j  ""  []  ()  set()  {}  None

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    name =0
return render(request, "", {"name": name})

HelloWorld/templates/ file code:

{{ name|default:"666" }}

Visit http://127.0.0.1:8000/runoob again to see the page:

(2)length

Returns the length of the object, applicable to strings and lists.

Dictionaries return the number of key-value pairs, collections return the length after de-duplication.

HelloWorld/HelloWorld/ file code:

from  import render

def runoob(request):
    name =""
    return render(request, "", {"name": name})

HelloWorld/templates/ file code:

{{ name|length}}

Visit http://127.0.0.1:8000/runoob again to see the page:

(3)filesizeformat

Display the file size in a more readable way (i.e. '13 KB', '4.1 MB', '102 bytes', etc.).

Dictionaries return the number of key-value pairs, collections return the length after de-duplication.

HelloWorld/HelloWorld/ file code:

from  import render

def runoob(request):
    num=1024
    return render(request, "", {"num": num})

HelloWorld/templates/ file code:

{{ num|filesizeformat}}

Visit http://127.0.0.1:8000/runoob again to see the page:

(4)date

Formats a date variable according to a given format.

Format Y-m-d H:i:s returnYear-Month-Day Hours:Minutes:Seconds The format time of the

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
import datetime
    now  =()
return render(request, "", {"time": now})

HelloWorld/templates/ file code:

{{ time|date:"Y-m-d" }}

Visit http://127.0.0.1:8000/runoob again to see the page:

(5)truncatechars

If the string contains more total characters than the specified number of characters, then the trailing portion is truncated.

The truncated string will end with ... End.

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    views_str = ""
return render(request, "", {"views_str": views_str})

HelloWorld/templates/ file code:

{{ views_str|truncatechars:2}}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

(6)safe

Marks strings as safe without escaping.

Safe can only be used if you want to make sure that the data coming through is absolutely safe.

Same effect as mark_safe on the backend.

Django automatically escapes the syntax of the tags passed to the HTML file, invalidating their semantics. Adding a safe filter tells Django that the data is safe and does not need to be escaped in order for the semantics of the data to take effect.

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    views_str = "<a href='/'>click to jump</a>"
return render(request, "", {"views_str": views_str})

HelloWorld/templates/ file code:

{{ views_str|safe }}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

5、if/else label

The basic syntax format is as follows:

{% if condition %}
     ... display
{% endif %}

Or:

{% if condition1 %}
   ... display 1
{% elif condition2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

If/else support nesting.

The {% if %} tag accepts the and, or or not keywords to make a judgment on multiple variables, or to invert a variable (not ), for example:

{% if athlete_list and coach_list %}
     athletes cap (a poem) coaches Variables are available。
{% endif %}

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    views_num = 88
return render(request, "", {"num": views_num})

HelloWorld/templates/ file code:

{%if num > 90 and num <= 100 %}
talented
{% elif num > 60 and num <= 90 %}
eligible (voter etc)
{% else %}
Go ahead and play.~
{% endif %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

6, for tags

{% for %} allows us to iterate over a sequence.

Similar to the case of Python's for statement, the loop syntax is for X in Y, where Y is the sequence to be iterated over and X is the name of the variable to be used in each particular loop.

The template system renders everything between {% for %} and {% endfor %} in each loop.

For example, given a list of athletes athlete_list variable, we can use the following code to display this list:

<ul>
{% for athlete in athlete_list %}
    <li>{{  }}</li>
{% endfor %}
</ul>

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    views_list = ["","1","2","3",]
return render(request, "", {"views_list": views_list})

HelloWorld/templates/ file code:

{% for i in views_list %}
{{ i }}
{% endfor %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

Adding a reversed to a label causes the list to be iterated backwards:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

HelloWorld/templates/ file code:

{% for i in views_list  reversed%}
{{ i }}
{% endfor %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

Iterative dictionary: You can use the dictionary directly.items method with the unwrap of the variable to get the key and value respectively.

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    views_dict = {"name":"","age":18}
return render(request, "", {"views_dict": views_dict})

HelloWorld/templates/ file code:

{% for i,j in views_dict.items %}
{{ i }}---{{ j }}
{% endfor %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

The loop number can be obtained from the {{forloop}} variable in the {% for %} tag.

  • : Get cycle number in order, counting from 1
  • forloop.counter0: get the loop number in order, starting from 0
  • : flashback to get the loop number, ending with the number 1
  • forloop.revcounter0: flashback to get loop number, ending with 0
  • (usually used with if tags): True for the first piece of data, False for the rest.
  • (usually used with if tags): True for the last piece of data, False for the rest of the data.

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
     views_list = ["a", "b", "c", "d", "e"]
return render(request, "", {"listvar": views_list})

HelloWorld/templates/ file code:

{% for i in listvar %}
    {{  }}
    {{ forloop.counter0 }}
    {{  }}
    {{ forloop.revcounter0 }}
    {{  }}
    {{  }}
{% endfor %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

{% empty %}

Optional {% empty %} clause: Execute when the loop is empty (i.e., in followed by a boolean value of False).

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
  views_list = []
return render(request, "", {"listvar": views_list})

HelloWorld/templates/ file code:

{% for i in listvar %}
    {{ forloop.counter0 }}
{% empty %}
    empty (argument, head etc)~
{% endfor %}

Visit visit http://127.0.0.1:8000/runoob again to see the page:

The {% for %} tags can be nested:

{% for athlete in athlete_list %}
    <h1>{{  }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}

7, ifequal/ifnotequal tags

The {% ifequal %} tag compares two values and displays all values in {% ifequal %} and {% endifequal %} when they are equal.

The following example compares two template variables, user and currentuser.

{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}

Similar to {% if %}, {% ifequal %} supports the optional {% else%} tag:8

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}

8, note labels

Django annotations use {# #}.

{# This is a note #}

9, include tags

The {% include %} tag allows the inclusion of other templates in the template.

The following examples all contain templates:

{% include "" %}

III. csrf_token

csrf_token is used in form forms for cross-site request forgery protection.

If you don't use the {% csrf_token %} tag, you will get a 403 permission error if you have to jump to the page again when using the form form.

The {% csrf_token %} tag is used to submit the data in the form before it succeeds.

Parsing:

First, a request is sent to the browser to get the login page. At this point, the middleware csrf automatically generates a hidden input tag whose value attribute is a random string, and the user gets the login page as well as the hidden input tag.

Then, when the user needs to use the form form to submit data, it will carry this input label together with the submission to the middleware csrf, the reason is that the form form submit data, will include all the input label, the middleware csrf receives the data, it will be judged, this random string is not the first time it sends to the user of the one, if it is, then the data is submitted successfully, if not, then the data is submitted successfully. If it is, then the data is submitted successfully, if not, then it returns 403 permission error.

IV. Customized labels and filters

1. In the app directory, createtemplatetags directory (directory name can only be templatetags).

2. Create any py file in the templatetags directory, for example:my_tags.py

3. under that py file:

from django import template

register = ()   #registerThe name is fixed,immutable

4. Use the decorator @ custom filter.

Attention:The decorator can only have a maximum of 2 parameters.

@
def my_filter(v1, v2):
    return v1 * v2

5. Use the decorator @register.simple_tag to customize the tag.

@register.simple_tag
def my_tag1(v1, v2, v3):
    return v1 * v2 * v3

6. Before using custom tags and filters, import the py file at the top of the html file body.

{% load my_tags %}

7. Use custom filters in HTML.

{{ 11|my_filter:22 }}

8. Use custom tags in HTML.

{% my_tag1 11 22 33 %}

9. Semanticized labels

Import mark_safe in that py file.

from  import mark_safe

When defining tags, use the mark_safe method to semanticize the tag, which is equivalent to the html() method in jQuery.

The effect is the same as the filter safe in the front-end HTML file.

@register.simple_tag
def my_html(v1, v2):
    temp_html = "<input type='text' id='%s' class='%s' />" %(v1, v2)
    return mark_safe(temp_html)

Use this custom tag in HTML to dynamically create tags in the page.

{% my_html "zzz" "xxx" %}

V. Configuring static files

1. Create a statics directory in the root directory of your project.

2. Add the following configuration to the bottom of the settings file:

STATIC_URL = '/static/' # Alias
STATICFILES_DIRS = [ 
    (BASE_DIR, "statics"), 
]

3, in the statics directory to create css directory, js directory, images directory, plugins directory, respectively, put css files, js files, images, plug-ins.

4. Put the bootstrap framework into the plugins directory plugins.

5. Introduce bootstrap in the head tag of the HTML file.

Note: Instead of the directory statics, use the alias static in the configuration file for the reference path.

<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/" rel="external nofollow" >

To use it in a template you need to add the {% load static %} code, in the following example we are bringing in images from a static directory.

HelloWorld/HelloWorld/ file code:

from  import render
def runoob(request):
    name =""
return render(request, "", {"name": name})

HelloWorld/templates/ file code:

{% load static %}
{{name}}<img src="{% static "images/" %}" alt="runoob-logo">

Visit visit http://127.0.0.1:8000/runoob again to see the page:

VI. Template inheritance

Templates can be reused with inheritance to reduce redundant content.

The header and footer content of a web page are generally the same, so we can reuse them through template inheritance.

Parent templates are used to place reusable content, and child templates inherit the content of the parent template and place their own content.

1. Parent template

Tags block... .endblock. A reserved area in the parent template, which is reserved for the child template to be filled with differentiated content; different reserved areas cannot have the same name.

{% block name (of a thing) %} 
Area reserved for sub-templates,You can set the default content of the settings
{% endblock name (of a thing) %}

2、Sub-template

Child templates inherit from the parent template using the tag extends:

{% extends "Parent template path"%}

If the child template does not set the content of the reserved area of the parent template, it will use the default content set in the parent template, of course, you can also do neither, it will be empty.

The child template sets the contents of the parent template's reserved area:

{ % block name (of a thing) % }
element 
{% endblock name (of a thing) %}

Next, we create the templates directory of the previous project and add the file with the following code:

HelloWorld/templates/ file code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>()</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p> Django test (machinery etc)。</p>
    {% block mainbody %}
       <p>original</p>
    {% endblock %}
</body>
</html>

In the above code, the block tag named mainbody is the part that can be replaced by the successors.

All {% block %} tags tell the template engine that the sub-template can overload these sections.

and replace the specific block with the following modified code:

HelloWorld/templates/ file code:

{%extends "" %}
 
{% block mainbody %}
<p>inherited  file</p>
{% endblock %}

The first line of code shows that the file is inherited. As you can see, the block tag with the same name is used here to replace the corresponding block.

Revisit the address http://127.0.0.1:8000/runoob with the following output:

To this point this article on the use of Django framework template is introduced to this article. I hope it will help you to learn, and I hope you support me more.