Context usage in Python's Django framework

Source: Internet
Author: User
Tags xml parser

Context usage in Python's Django framework


Once you create a Template object, you can use the context to pass the data to it. A context is a collection of variables and their values.

Context is represented in Django as the context class, in the Django.template module. Her constructor has an optional parameter: A dictionary-mapped variable and their value. Call the render () method of the template object and pass the context to populate the template:

>>> 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 point out that the value returned by T.render (c) is a Unicode object, not a normal Python string. You can differentiate it by the U before the string. In the framework, Django will always use Unicode objects instead of ordinary strings. If you understand how convenient this is to you, be as thankful as you can about what Django is doing for you in a methodical way. Don't worry if you don't understand what you've benefited from. You just need to know that Django's support for Unicode will allow your application to easily handle a wide variety of character sets, not just basic A-Z English characters. The dictionary data type of the

dictionary and Contexts

Python is a mapping of keywords and their values. The context is similar to a dictionary, and the context provides more functionality. The

variable name must start with an English character (A-Z or a-Z) and can contain numeric characters, underscores, and decimal points. (The decimal point has a special purpose here, we'll talk about it later) variables are case-sensitive.

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

>>> 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) &GT;&GT;&GT; 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 step through the code to analyze the following:

First we import the class Template and Context, which are all in the module django.template.

We save the original text of the template to the variable raw_template. Notice that we use three quotation marks to identify the text, because it can contain more than one line.

Next, we create a template object T, which takes raw_template as the parameter of the class constructor.

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

Then, we create a Context object, C. The parameter of the Context construct is the Python dictionary data type. Here we specify that the value of the parameter person_name is ' John Smith ', parameter Company's value is ' outdoor equipment ', and so on.

Finally, we call the render () method on the template object, passing the context parameter to it. This is the method of returning the rendered template, which replaces the template variable with the real value and executes the block label.

Note that the warranty paragraph is displayed because the value of Ordered_warranty is True. Note the time of the display, April 2, 2009, which is displayed as ' F J, Y ' format.

If you are a Python beginner, you may wonder why the output has a newline character (' \ n ') instead of a carriage return line? Because this is the reason for the Python interaction interpreter: Call T.render (c) to return a string, the interpreter defaults to show the actual content rendering of these strings, rather than printing the value of the variable. To display line breaks instead of ' \ n ', use the print statement: Print T.render (c).

This is the basic rule for using the Django template system: Writing templates, creating template objects, creating Context, calling the render () method.http://www.aichengxu.com/view/60625
same template, multiple contexts

Once you have a template object, you can render multiple context through it, 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



Whenever we can render multiple context using the same template source like this, it is more efficient to make only one template creation and then call the render () method multiple times:

# badfor name in (' John ', ' Julie ', ' Pat '): t = Template (' Hello, {{name}} ') Print T.render (Context ({' name ': name}) # Go ODT = 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 done in the background through a one-time call to a short regular expression. This contrasts with the XML-based template engine, which takes on the cost of the XML parser and tends to be several orders of magnitude slower than the Django template rendering engine.  

Context usage in Python's Django framework

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.