Getting started with Django (3) templates in Django

Source: Internet
Author: User

The input in the previous section is the return httpresponse () section in the view. The content in the function is <HTML> <body> ......

This means that front-end files must be written and printed every time, which is very troublesome. Generally, it includes many contents, such as JS files and CSS files. In addition, the design page is not easy to design, or it is well designed, and then paste the HTML string for output. HTML code and Python background Code are also mixed.

1. Custom,

Write data directly in the view. The newly created view (function) hello_who is as follows:

Def hello_who (request ):

T = template. template ('Hello {name }}')

C = template. Context ({'name': 'songjiang '})

Return httpresponse (T. Render (c ))

 

By creating a template, output hello, WHO

Here, who is named Song Jiang in Chinese ., If Chinese characters are displayed normally on the page, you need to set export age_code = 'zh-cn' in settings. py'

In the View File views. py, add # encoding = UTF-8 to the first line.

2. Use templates

Create a template file with any file name. The template file is the HTML foreground file. Similar to the ASPX page. Create a hello.html file first. As follows:

<HTML>

<Body>

<Div style = "color: red;"> <B> hello, {name }}</B> </div>

</Body>

</Html>

Load the template in the view and assign values to the variables.

Change the view hello_who:

Def hello_who (request ):

T = get_template('hello.html ')

Html = T. Render (context ({'name': 'songjiang '}))

Return httpresponse (HTML)

You can use a function to obtain the template and the rendering function, as shown below:
Def hello_who (request ):

Return render_to_response('hello.html ', {'name': 'songjiang '})

 

To use this function, you need to introduce:

From Django. Shortcuts import render_to_response

Return all defined mappings through locals ()

Def hello_who (request ):

Name = 'songjiang'

Return render_to_response('hello.html ', locals ())

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.