home PYTHONJAVA
 

Django template

In the previous chapter we used django.http.HttpResponse() to output "Hello World!". This approach mixes data with views and does not conform to Django's MVC thinking.

In this chapter we will give you a detailed introduction to the application of Django templates, which is a text that separates the presentation and content of a document.


Template application example

We will continue to create the templates directory under the HelloWorld directory and create a hello.html file in the previous section. The entire directory structure is as follows:

HelloWorld/
|-- HelloWorld
| |-- __init__.py
| |-- __init__.pyc
| |-- settings.py
| |-- settings.pyc
| |-- urls.py
| |-- urls.pyc
| |-- view.py
| |-- view.pyc
| |-- wsgi.py
| `-- wsgi.pyc
|-- manage.py
`--templates
    `-- hello.html

hello.html The file code is as follows:

HelloWorld/templates/hello.html File Code:

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

From the template we know that the variable uses double brackets.

Next we need to explain the path to the template file to Django, modify HelloWorld/settings.py, and modify the DIRS in TEMPLATES to [BASE_DIR+"/templates",] as follows: p>

HelloWorld/HelloWorld/settings.py File code:

...TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates ",], # Edit location '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', ], }, }, ] ...

We now modify view.py and add a new object to submit data to the template:

HelloWorld/HelloWorld/view.py File code:

# -*- coding: utf-8 -*- #from django.http import HttpResponse from django.shortcuts import render def hello(request): context = {} context['hello'] = 'Hello World!' return render(request, 'hello.html' , context)

You can see that we use render instead of the HttpResponse we used before. Render also uses a dictionary context as a parameter.

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

Revisit http://127.0.0.1:8000/hello to see the page:

This way we are done using the template to output the data, thus separating the data from the view.

Next we will introduce the syntax rules commonly used in templates.


Django template tag

if/else tag

The basic syntax is as follows:

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

or:

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

According to the condition, judge whether to output. If/else supports nesting.

The

{% if %} tag accepts the and , or or not keyword to determine multiple variables, or to invert the variable (not ), for example:

{% if athlete_list and coach_list % }
     Athletes and  coaches variables are available. 
{% endif %}

for tag

{% 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 iterate and X is the name of the variable to use in each particular loop.

In each iteration, the template system renders everything between {% for %} and {% endfor %}.

For example, given an athlete list athlete_list variable, we can use the following code to display this list:

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

Adding a reversed to the tag causes the list to be iterated in reverse:

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

The {% for %} tag can be nested:

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

ifequal/ifnotequal tag

The

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

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 %}

Comment tag

Django annotations use {# #}.

{# This is a Comments #}

Filter

The template filter can be modified before the variable is displayed. The filter uses the pipe character as follows:

{{ name|lower }}

After the {{ name }} variable is processed by the filter lower, the document uppercase conversion text is lowercase.

Filtering pipes can be *sleeved*, which means that the output of one filter pipe can be used as input to the next pipe:

{{ my_list|first|upper  }}

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

Some filters have parameters. The parameters of the filter follow the colon and are always enclosed in double quotes. E.g:

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

Adding a reversed to the tag causes the list to be iterated in reverse:

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

The {% for %} tag can be nested:

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

ifequal/ifnotequal tag

The

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

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 %}

Comment tag

Django annotations use {# #}.

{# This is a Comments #}

Filter

The template filter can be modified before the variable is displayed. The filter uses the pipe character as follows:

{{ name|lower }}

After the {{ name }} variable is processed by the filter lower, the document uppercase conversion text is lowercase.

Filtering pipes can be *sleeved*, which means that the output of one filter pipe can be used as input to the next pipe:

{{ my_list|first|upper  }}

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

Some filters have parameters. The parameters of the filter follow the colon and are always enclosed in double quotes. E.g:

{{ bio|truncatewords:"30" }}

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

Other filters:

  • addslashes : Add a backslash to any backslashes, single quotes, or double quotes.
  • 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.

include tag

The {% include %} tag allows you to include the contents of other templates in your template.

The following example contains the nav.html template:

{% include "nav .html" %}

Template inheritance

Templates can be reused in an inherited manner.

Next we will add the base.html file in the templates directory of the previous project, the code is as follows:

HelloWorld/templates/base.html File Code:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Welookups Tutorial (welookups.com)</title > </head> <body> <h1>Hello World!</h1 > <p>Welookups Tutorial Django Test. </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 sub-templates can override these sections.

Hello.html inherits base.html and replaces a specific block, hello.html The modified code is as follows:

HelloWorld/templates/hello.html File Code:

{%extends "base.html" %} {% block mainbody %} <p>inheritedbase .html File</p> {% endblock %}

The first line of code indicates that hello.html inherits the base.html file. As you can see, the block tag with the same name is used to replace the corresponding block of base.html.

Re-access the address http://127.0.0.1:8000/hello, the output is as follows:






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.