How to Use the python Django Template

Source: Internet
Author: User

Basic Template Introduction
A template is a text that is used to separate the representation and content of a document. A template defines placeholders and various basic logics (template tags) used to demonstrate how a document is displayed ). Templates are usually used to generate HTML, but Django templates can also generate any document based on text format.
To describe a project
1. Create a MyDjangoSite project. For more information, see the previous section.
2. Create a New templates folder in the MyDjangoSite (containing four files) folder directory.
3. Create the template file user_info.html under the just-created Template
Copy codeThe Code is as follows:
<Html>
<Meta http-equiv = "Content-type" content = "text/html; charset = UTF-8">
<Title> User Information </title>
<Head> <Body>
<H3> User information: <P> name: {name }}</p>
<P> age: {age }}</p>
</Body>
</Html>

Note: {name} is the template variable; {% if xx %}, and {% for x in list %} is the template tag.

4. Modify TEMPLATE_DIRS in settings. py.
Import OS. path
Add OS. path. join (OS. path. dirname (_ file _), 'templates'). replace ('\\','/'),
Copy codeThe Code is as follows:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates ".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.

# "E:/workspace/pythonworkspace/MyDjangoSite/templates ",
OS. path. join (OS. path. dirname (_ file _), 'templates'). replace ('\\','/'),
)

Description: Specifies the template loading path. OS. path. dirname (_ file _) is the file path of the current settings. py, and then connects to the templates path.

5. Create a view File view. py.
Copy codeThe Code is as follows:
# Vim: set fileencoding = UTF-8:

# From django. template. loader import get_template
# From django. template import Context
# From django. http import HttpResponse
From django. shortcuts import render_to_response

Def user_info (request ):
Name = 'zbw'
Age = 24
# T = get_template('user_info.html ')
# Html = t. render (Context (locals ()))
# Return HttpResponse (html)
Return render_to_response('user_info.html ', locals ())

Note: the basic rules of the Django Template system are: Write a Template, create a Template object, create a Context, and call the render () method.
You can see the comments in the above Code
# T = get_template('user_info.html ') # html = t. render (Context (locals ()))
# Return HttpResponse (html)
Get_template('user_info.html '), uses the django. template. loader. get_template () function, instead of manually loading the template from the file system. The get_template () function uses the Template Name as a parameter to locate the module location in the file system, open the file, and return a compiled Template object.
The render (Context (locals () method receives a set of variable context. It returns a template-based display string, and the variables and labels in the template are replaced by the context value. Context (locals () is equivalent to Context ({'name': 'zbw ', 'age': 24}), locals () it returns a dictionary to map the names and values of all local variables.
Render_to_response Django provides a shortcut for you to load a template file at a time, render it, and return it as HttpResponse.

6. Modify urls. py
 Copy codeThe Code is as follows:
From django. conf. urls import patterns, include, url
From MyDjangoSite. views import user_info

# Uncomment the next two lines to enable the admin:
# From django. contrib import admin
# Admin. autodiscover ()

Urlpatterns = patterns ('',
# Examples:
# Url (R' ^ $ ', 'mydjangosite. views. home', name = 'home '),
# Url (R' ^ MyDjangoSite/', include ('mydjangosite. foo. urls ')),

# Uncomment the admin/doc line below to enable admin documentation:
# Url (R' ^ admin/doc/', include ('django. contrib. admindocs. urls ')),

# Uncomment the next line to enable the admin:
# Url (R' ^ admin/', include (admin. site. urls )),

Url (R' ^ u/$ ', user_info ),

)
 

7. Start the Development Server
A basic simple template application is complete. Start the service to see the effect!
Effect


Template inheritance
Reduce repeated Writing of the same Code and reduce maintenance costs. View the application directly.
1. Create/templates/base.html
Copy codeThe Code is as follows:
<Html>
<Meta http-equiv = "Content-type" content = "text/html; charset = UTF-8">
<Title >{% block title % }{% endblock %} </title>
<Head> <Body>
<H3 >{% block headTitle %}{% endblock %}{% Block content %} {% endblock %}

{% Block footer %}
<H3> Hey, this is an inherited template {% Endblock %}
</Body>
</Html>

2. Modify/template/user_info.html to create product_info.html
Urser_info.html
Copy codeThe Code is as follows:
{% Extends "base.html" %}

{% Block title %} user information {% endblock %}


<H3 >{% block headTitle %} user information: {% endblock %}

{% Block content %}
<P> name: {name }}</p>
<P> age: {age }}</p>
{% Endblock %}

Product_info.html
Copy codeThe Code is as follows:
{% Extends "base.html" %}
{% Block title %} product information {% endblock %}
<H3 >{% block headTitle %} product information: {% endblock %} {% Block content %}
{ProductName }}
{% Endblock %}

3. Write view logic and modify views. py
Copy codeThe Code is as follows:
# Vim: set fileencoding = UTF-8:

# From django. template. loader import get_template
# From django. template import Context
# From django. http import HttpResponse
From django. shortcuts import render_to_response

Def user_info (request ):
Name = 'zbw'
Age = 24
# T = get_template('user_info.html ')
# Html = t. render (Context (locals ()))
# Return HttpResponse (html)
Return render_to_response('user_info.html ', locals ())

Def product_info (request ):
ProductName = 'amoxicillin capsules'
Return render_to_response('product_info.html ', {'productname': productName })

4. Modify urls. py
Copy codeThe Code is as follows:
From django. conf. urls import patterns, include, url
From MyDjangoSite. views import user_info, product_info

# Uncomment the next two lines to enable the admin:
# From django. contrib import admin
# Admin. autodiscover ()

Urlpatterns = patterns ('',
# Examples:
# Url (R' ^ $ ', 'mydjangosite. views. home', name = 'home '),
# Url (R' ^ MyDjangoSite/', include ('mydjangosite. foo. urls ')),

# Uncomment the admin/doc line below to enable admin documentation:
# Url (R' ^ admin/doc/', include ('django. contrib. admindocs. urls ')),

# Uncomment the next line to enable the admin:
# Url (R' ^ admin/', include (admin. site. urls )),

Url (R' ^ u/$ ', user_info ),
Url (R' ^ p/$ ', product_info ),
)

5. The Service Startup effect is as follows:

Related Article

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.