How to use Python Django templates

Source: Internet
Author: User
A template is a text that separates the representation and content of a document. The template defines the placeholder and various basic logic (template tags) that are used to standardize how the document should be displayed. Templates are often used to generate HTML, but Django templates can also produce any document based on text format.
to a project description
1, the establishment of Mydjangosite project specific not much to say, refer to the front.
2, in Mydjangosite (contains four files) folder directory to create a new Templates folder template.
3, in the newly established template under the template version of the file user_info.html

  
 
    User Information        

User information:

Name: {{name}}

Age: {{ages}}

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

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

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 the use of 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 file path of the current settings.py, and then the templates path is connected.
5. New View File view.py

#vim: Set Fileencoding=utf-8: #from django.template.loader import get_template#from django.template import Context#from Django.http Import httpresponsefrom django.shortcuts import render_to_responsedef user_info (Request):  name = ' ZBW ' Age  =  #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 the Django template system: Writing templates, creating template objects, creating Context, calling the render () method.

You can see the comment 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 an argument, finds the location of the module in the file system, opens the file, and returns a compiled template object.
The render (context (locals ())) method receives an 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 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 shortcut for you to load a template file once, render it, and return it as a httpresponse.

6, modify the urls.py

From Django.conf.urls import patterns, include, Urlfrom mydjangosite.views import user_info# Uncomment the next and 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.co Ntrib.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 complete, start the service to see the effect!
Effect

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

  
 
    {% block title%} {% Endblock%}        

{% block Headtitle%} {% Endblock%}

{% block content%} {% Endblock%} {% block footer%}

Hey, this is a copy of the template.

{% endblock%}

2, modify/template/user_info.html, and new product_info.html
Urser_info.html

{% block Headtitle%} user information: {% Endblock%}

{% block content%}

Name: {{name}}

Age: {{ages}}

{% Endblock%}

Product_info.html

{% extends "base.html"%} {% block title%} product information {% Endblock%}

{% block Headtitle%} product information: {% Endblock%}

{% block content%} {{ProductName}} {% Endblock%}

3, write the view logic, modify the views.py

#vim: Set Fileencoding=utf-8: #from django.template.loader import get_template#from django.template import Context#from Django.http Import httpresponsefrom django.shortcuts import render_to_responsedef user_info (Request):  name = ' ZBW ' Age  =  #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 '  

4, modify the urls.py

From Django.conf.urls import patterns, include, Urlfrom mydjangosite.views import user_info,product_info# uncomment the N  Ext. 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/', I Nclude (Admin.site.urls)),  URL (r ' ^u/$ ', user_info),  

5, start the service effect as follows:

The above is the whole content of this article, I hope that everyone's study has helped.

  • 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.