Django Primer Example of the liberated Jiang GE--03 so-called Iraqis (template and template processing)

Source: Internet
Author: User

In the previous program, we directly generated a string, which is returned to the client as an HTTP reply. Django.http.HttpResponse () was used in this process.

In this kind of response generation process, we actually mix the data and the view format into the string above. Seemingly convenient, but for our management to bring difficulties. Imagine a mature website where the display format will have many repetitions. If you can separate the data from the view format, you can reuse the same view format.

Django's own template system, you can separate the view format, as a template to use. In this way, not only can the view be easily modified, but also the program will look nice and elegant.

1. Initial experience of the template

Let's take a standalone templay.html file as a template. It is placed under the templates/west/folder. The structure of the file system is now:

    1. mysite/
    2. ├──mysite
    3. ├──templates
    4. │└──west
    5. └──west


The content of the templay.html file is:

Can see, in this file, there is a strange double parenthesis wrapped up by strangers. This is where our future data comes in. The associated format control, the

We need to specify the search path to the Django template file, modify the mysite/settings.py, and add:

    1. # Template Dir
    2. Template_dirs = (
    3. Os.path.join (Base_dir, ' templates/west/'),
    4. )


If there are other paths to hold the template, you can increase the elements in that tuple so that Django can find the template you want.


We will now modify west/views.py and add a new object to submit the data to the template:

    1. #-*-Coding:utf-8-*-
    2. #from django.http Import HttpResponse
    3. From django.shortcuts Import Render
    4. def templay (Request):
    5. context = {}
    6. context[' label '] = ' Hello world! '
    7. return render (Request, ' templay.html ', context)


As you can see, we use render here instead of the previously used HttpResponse. Render also uses a dictionary context as a parameter. This is our data.
The key value of the element in the context is ' label ', which corresponds to the name of the "Stranger" just now. Thus, the value of the ' label ' element in the context fills the hole in the template to form a complete HTTP reply.

As a little exercise in the content of the previous section, modify the west/urls.py yourself so that the Http://127.0.0.1:8000/west/templay URL request can find the corresponding View object.

To access Http://127.0.0.1:8000/west/templay, you can see the page:

2. Process
Look at the whole process again. Templay () in west/views.py passes the environment data context to the template templay.html when it returns. Django generates the final HTTP reply by placing the corresponding data in the corresponding location in the template, based on the key values in the context element.

This template system can work with other Django functions. In the previous section, we extracted the data from the database. If you put the data in the database into the context, you can transfer the data from the database to the template.

Modify the staff in the last west/views.py:

    1. DEF staff (request):
    2. Staff_list = Character.objects.all ()
    3. STAFF_STR = Map (str, staff_list)
    4. context = {' label ': '. Join (STAFF_STR)}
    5. return render (Request, ' templay.html ', context)


Exercise: Show the staff page above.

3. Circulation and selection

Django actually provides a rich template language that allows for a limited amount of programming within the template, making it easier to write views and transfer data.

Let's try the most common loops and choices below.


The data in the above staff is actually a data container with three elements. Just now we are connecting three elements into a string transfer.

In fact, using the template language, we can directly transfer the data container itself, and then loop the display. Modify staff () to:

    1. DEF staff (request):
    2. Staff_list = Character.objects.all ()
    3. return render (Request, ' templay.html ', {' Staffs ': Staff_list})

The three objects queried from the database are in Staff_list. We send staff_list directly to the template.

Modify the template templay.html to:

    1. {% for item in staffs%}
    2. <p>{{Item.id}}, {{item}}</p>
    3. {% ENDFOR%}

We define a for in the template in a way similar to the for loop in Python to show each element in the staffs.

You can also see that the object. The reference to the property name can be used directly in the template.

The selection structure is similar to Python. Depending on whether the transmitted data is True,django, select whether or not to display. Use the following methods:

    1. {% if condition1%}
    2. ... display 1
    3. {% elif Condiiton2%}
    4. ... display 2
    5. {% Else%}
    6. ... display 3
    7. {% ENDIF%}

One of the elif and else is the same as in Python and can be omitted.

4. Template inheritance

Templates can be reused in a way that inherits. Below we use templay.html to inherit base.html. In this way, we can use the main body of the base.html and replace only the specific parts.

New templates/west/base.html:

    1. <title>templay</title>
    2. <body>
    3. {% block mainbody%}
    4. <p>original</p>
    5. {% Endblock%}
    6. </body>


In this page, the block tag named Mainbody is the part that can be replaced by the successor.


We inherit base.html in the following templay.html and replace the specific block:

    1. {% extends "base.html"%}
    2. {% block mainbody%}
    3. {% for item in staffs%}
    4. <p>{{item.id}},{{item.name}}</p>
    5. {% ENDFOR%}
    6. {% Endblock%}


The first sentence shows that templay.html inherits from Base.html. As you can see, the block tag of the same name here replaces the corresponding block of base.html.

5. Summary

Use templates to implement view separation.

Data passing, template variables, template looping and selection, template inheritance.

Django Primer Example of the liberated Jiang GE--03 so-called Iraqis (template and template processing)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.