Python Django template usage, pythondjango Template

Source: Internet
Author: User

Python Django template usage, pythondjango Template

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

<Html> <meta http-equiv = "Content-type" content = "text/html; charset = UTF-8 "> <title> User Information </title> 

Description: {Name} is the template variable; {% if xx %}, {% 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 ('\\','/'),

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

#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 = 24  #t = get_template('user_info.html')  #html = t.render(Context(locals()))  #return HttpResponse(html)  return render_to_response('user_info.html',locals())

Description: Basic Rules of the Django Template system: 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 '),
The django. template. loader. get_template () function is used 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

from django.conf.urls import patterns, include, urlfrom 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

<Html> <meta http-equiv = "Content-type" content = "text/html; charset = UTF-8 "> <title >{% block title %}{% endblock %}</title> 

2. Modify/template/user_info.html to create product_info.html
Urser_info.html

{% Extends "base.html" % }{% block title %} user information {% endblock %} 

Product_info.html

{% Extends "base.html" % }{% block title %} product information {% endblock %} 

3. Write view logic and modify 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 = 24 # t = get_template('user_info.html') # html = t. render (Context (locals () # return HttpResponse (html) return response ', locals () def product_info (request): productName = 'amoxicillin capsules 'Return render_to_response('product_info.html ', {'productname ': productName })

4. Modify urls. py

from django.conf.urls import patterns, include, urlfrom 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:

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Python Django template usage (image and text)
  • How to Create a template library in the Python Django framework
  • Introduction to the template fragment cache in the Django framework of Python

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.