How to use Python Django templates (text) _python

Source: Internet
Author: User
Tags documentation inheritance

Template Basic Introduction
A template is a text that separates the presentation and content of a document. Templates define placeholders and a variety of basic logic (template labels) for each part of how the document should be displayed. Templates are typically used to generate HTML, but Django templates can also produce any text-based document.
to a project description
1, the establishment of MYDJANGOSITE projects specifically not to say, refer to the front.
2, in the Mydjangosite (contains four files) folder directory to create a new Templates folder storage template.
3, in the newly-built template version of the document User_info.html

Copy Code code as follows:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> User Information </title>
<body>
<p> name:{{name}}</p>
<p> Age:{{age}}</p>
</body>

Description: {{name}} is called template variable; {% if xx%}, {% for x in list%} template label.

4, modify the Template_dirs in settings.py
Importing Import Os.path
Add Os.path.join (Os.path.dirname (__file__), ' Templates '). replace (' \ \ ', '/'),

Copy Code code as follows:

Template_dirs = (
# put strings this, 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/mydjangosite/templates",
Os.path.join (Os.path.dirname (__file__), ' Templates '). replace (' \ \ ', '/'),
)


Description: Specifies the template load path. where Os.path.dirname (__file__) is the current settings.py file path, and then connects to the templates path.

5. New View File view.py

Copy Code code 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 ())


Description: The basic rules of Django Template system: Write template, create Template object, create context, call render () method.
You can see the annotation section in the code above
#t = get_template (' user_info.html ') #html = T.render (Context (locals ())
#return HttpResponse (HTML)
Get_template (' user_info.html ') uses the function django.template.loader.get_template () instead of manually loading the template from the file system. The Get_template () function takes the template name as the parameter, finds the location of the module in the file system, opens the file, and returns a compiled template object.
The render (Locals ()) method receives the incoming set of variable context. It will return a template based presentation string, and the variables and tags in the template will be replaced by the context value. Where the context (locals ()) is equivalent to the context ({' name ': ' ZBW ', ' Age ':}), locals () it returns a dictionary that maps the names and values of all local variables.
Render_to_response Django provides a quick way to load a template file, render it, and then return it as a httpresponse.

6. Modify urls.py

Copy Code code 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
Basic a simple template application is completed, start service to see the effect!
Effect as shown:


The Inheritance of templates
Reduce the repetition of writing the same code, and reduce maintenance costs. See the application directly.
1. New/templates/base.html

Copy Code code as follows:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>{% block title%}{% Endblock%}</title>
<body>
{% block content%} {% Endblock%}

{% block footer%}
{% endblock%}
</body>


2, modify/template/user_info.html, and new product_info.html
Urser_info.html
Copy Code code as follows:

{% extends ' base.html '%}

{% block title%} user information {% Endblock%}


{% block content%}
<p> name:{{name}}</p>
<p> Age:{{age}}</p>
{% Endblock%}


Product_info.html
Copy Code code as follows:

{% extends ' base.html '%}
{% block title%} product information {% Endblock%}
{% block content%}
{{ProductName}}}
{% Endblock%}

3, write the view logic, modify views.py
Copy Code code 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 capsule '
Return Render_to_response (' product_info.html ', {' ProductName ':p Roductname})

4. Modify urls.py

Copy Code code 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, start the service effect as follows:

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.