Use the Context in the Django framework of Python, djangocontext

Source: Internet
Author: User
Tags xml parser

Use the Context in the Django framework of Python, djangocontext

Use Context in the Django framework of Python

Recently I have compiled some Python knowledge. Once you create a Template object, you can use context to pass data to it. A context is a collection of variables and their values.
Context is represented as the Context class in Django, In the django. template module. Her constructor has an optional parameter: a dictionary ing variable and their values. Call the render () method of the Template object and pass context to fill the Template. Http://www.aichengxu.com/view/60625

>>> from django.template import Context, Template>>> t = Template('My name is {{ name }}.')>>> c = Context({'name': 'Stephane'})>>> t.render(c)u'My name is Stephane.'


We must note that the value returned by t. render (c) is a Unicode object, not a common Python string. You can use the u before the string to distinguish. In the Framework, Django will always use Unicode objects instead of common strings. If you understand how convenient this is, try to appreciate Django's well-organized work behind the scenes. Don't worry if you don't understand what you have benefited from it. The only thing you need to know about Django's Unicode support will make it easy for your application to handle a wide variety of character sets, not just basic A-Z English characters.

Dictionary and Contexts

The dictionary data type of Python is a ing between keywords and their values. Context is similar to the dictionary. Context also provides more functions.

The variable name must start with an English character (A-Z or a-z) and can contain numbers, underscores, and decimal places. (The decimal point has a special purpose here. We will talk about it later) variables are case sensitive.

The following is an example of writing and rendering a template:

>>> from django.template import Template, Context>>> raw_template = """<p>Dear {{ person_name }},</p>...... <p>Thanks for placing an order from {{ company }}. It's scheduled to... ship on {{ ship_date|date:"F j, Y" }}.</p>...... {% if ordered_warranty %}... <p>Your warranty information will be included in the packaging.</p>... {% else %}... <p>You didn't order a warranty, so you're on your own when... the products inevitably stop working.</p>... {% endif %}...... <p>Sincerely,<br />{{ company }}</p>""">>> t = Template(raw_template)>>> import datetime>>> c = Context({'person_name': 'John Smith',...   'company': 'Outdoor Equipment',...   'ship_date': datetime.date(2009, 4, 2),...   'ordered_warranty': False})>>> t.render(c)u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from OutdoorEquipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>Youdidn't order a warranty, so you're on your own when\nthe productsinevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment</p>"


Let's analyze this code step by step:

First, we import the (import) class Template and Context, both of which are in the module django. template.

We save the original template text to the variable raw_template. Note that we use three quotation marks to identify the text, because it can contain multiple lines.

Next, we create a Template object t and use raw_template as the parameter of the Template class constructor.

We import the datetime module from the Python standard library and will use it later.

Then, we create a Context object, c. The parameters constructed by Context are Python Dictionary data types. Here, we specify that the value of the person_name parameter is 'John Smith ', and the value of the company parameter is 'outdoor Equipment.

Finally, we call the render () method on the template object and pass the context parameter to it. This is the method to return the rendered template. It replaces the template variable with the actual value and execution block label.

Note that warranty paragraph is displayed because the value of ordered_warranty is True. Note that the display of time is in the format of 'f j, y.

If you are a beginner in Python, you may wonder why the output contains the carriage return character ('\ n') instead of the carriage return character? This is because of the Python interactive Interpreter: Call t. render (c) to return strings. The Interpreter displays the real content of these strings by default, instead of printing the value of this variable. To display a line feed instead of '\ n', use the print statement: print t. render (c ).

This is the basic rule for using the Django Template system: Write a Template, create a Template object, create a Context, and call the render () method.

Multiple contexts in the same template

Once a template object is available, you can use it to render multiple contexts, for example:

>>> from django.template import Template, Context>>> t = Template('Hello, {{ name }}')>>> print t.render(Context({'name': 'John'}))Hello, John>>> print t.render(Context({'name': 'Julie'}))Hello, Julie>>> print t.render(Context({'name': 'Pat'}))Hello, Pat


At any time, we can use the same template source to render multiple contexts, create a template only once, and call the render () method multiple times for rendering to be more efficient:

# Badfor name in ('John', 'Julie', 'Pat'):  t = Template('Hello, {{ name }}')  print t.render(Context({'name': name}))# Goodt = Template('Hello, {{ name }}')for name in ('John', 'Julie', 'Pat'):  print t.render(Context({'name': name}))


Django template Parsing is fast. Most of the parsing work is completed by calling the short regular expression at one time in the background. This is in stark contrast to the XML-based template engine, which bears the XML Parser overhead and is generally several orders of magnitude slower than the Django template rendering engine.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.