Latest web development tutorials

Django template

In the last chapter we use django.http.HttpResponse () to output "Hello World!". The way the data are mixed together with a view, does not meet the MVC thought of Django.

This chapter we will explain to you Django application template, the template is a text for presentation and content separate document.


Template Application Examples

We followed the previous section of the project will be created under HelloWorld directory templates directory and establish hello.html file, 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 file code is as follows:

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

We know from the template variable to use double parentheses.

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates",],
        '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, add a new object, for submitting data to the template:

# -*- 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)

We can see that we used here instead render HttpResponse before use. render also uses a dictionary context as a parameter.

Key elements in the context dictionary "hello" correspond to the variables in the template "{{hello}}".

Then visit visit http://192.168.45.3:8000/hello/, you can see the page:

Then we completed the template to use the output data, enabling data view separation.

Next, we will introduce the common template syntax rules.


Django template tags

if / else tag

The basic syntax is as follows:

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

or:

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

According to the conditions to determine whether output. if / else supports nested.

{% If%} tag accepts and, or or not to make a judgment on the keywords to multiple variables, or variables negated (not), for example:

{% if athlete_list and coach_list %}
     athletes 和 coaches 变量都是可用的。
{% endif %}

for labels

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

And Python's case for similar statements, loop syntax is for X in Y, Y is the sequence to loop over and X is a variable name used in each particular cycle.

Each time through the loop, the template system will render all {% for%} {% endfor%} content between and.

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

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

Label to add a list to be reversed so that the reverse iterator:

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

You can be nested {% for%} tag:

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

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

The following example compares the template variables user and two currentuser:

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

And {% if%} Similarly, {% ifequal%} supports an optional {% else%} tag: 8

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

Notes Tab

Django annotations using {##}.

{# 这是一个注释 #}

filter

Template filter can be displayed in the variable before modifying it, the filter pipe character, as follows:

{{ name|lower }}

{{Name}} variable after being lower filter processing, document convert text to uppercase lowercase.

Filter pipe socket can be * *, both say, an output filter pipes and can be used as input to the next pipeline:

{{ my_list|first|upper }}

The first element of the above example and convert it to uppercase.

Some filters have parameters. After the filter parameters followed by a colon and always double quotes. E.g:

{{ bio|truncatewords:"30" }}

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

Other Filters:

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

include tag

{% Include%} tag allows other content that contains a template in the template.

The following two examples are included nav.html template:

{% include "nav.html" %}

Template inheritance

Templates can inherit way to achieve multiplexing.

Next, we create templates directory before adding base.html project file, as follows:

<html>
  <head>
    <title>Hello World!</title>
  </head>

  <body>
    <h1>Hello World!</h1>
    {% block mainbody %}
       <p>original</p>
    {% endblock %}
  </body>
</html>

The above code, block tag named mainbody is that it can be successors to replace parts.

All {% block%} tag tells the template engine that child templates can override these parts.

hello.html inherited base.html, and replace specific block, the code hello.html modified as follows:

{% extends "base.html" %}

{% block mainbody %}
<p>继承了 base.html 文件</p>
{% endblock %}

The first line of code illustrates hello.html inherited base.html file. We can see here the same name of block tag to replace base.html corresponding block.

Revisit address http://192.168.45.3:8000/hello/, output results are as follows: