Wednesday, January 11, 2017

Django - 022 - Dictionaries and contexts

A Python dictionary is a mapping between known keys and variable values. A context is similar to a dictionary, but a Context provides additional functionality.

Variable names must begin with a letter (A-Z or a-z) and may contain more letters, digits, underscores and dots. (Dots are a special case we will get to in a moment.) Variable names are case sensitive. Here is an example of template compilation and rendering, using a template similar to the example previously shown:
~/Documents/my_d3_project/django/myD3site $ python manage.py shell -i python
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 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 did not order a warranty, so you are 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':'Siddharth Mehta',})
>>> c = Context({'person_name':'Siddharth Mehta',  
...     'company':'Outdoor Equipment',
...     'ship_date':datetime.date(2017,1,8),
...     'ordered_warranty':False})
>>> t.render(c)
u" <p> Dear Siddharth Mehta, </p>\n\n<p> Thanks for placing an order from Outdoor Equipment. It's scheduled to\nship on January 8, 2017.</p>\n\n\n<p> You did not order a warranty, so you are on your own when the products\ninevitably stop working. </p>\n\n\n<p>Sincerely, <br /> Outdoor Equipment </p> "
>>> 

  • First, we import the classes Template and Context, which both live in the module django.template.
  • We save the raw text of our template into the variable raw_template. Note that we use triple quote marks to designate the string, because it wraps over multiple lines; in contrast, string within single quote marks cannot be wrapped over multiple lines.
  • Next, we create a template object, t, by passing raw_template to the Template class constructor.
  • We import the datetime module from Python's standard library, because we will need it in the following statement.
  • Then, we create a context object, c. The Context constructor takes a Python dictionary, which maps variable names to values. Here, for example, we specify that the person_name is "John Smith", company is "Outdoor equipment", and so forth.
  • Finally, we call the render() method on our template object, passing it the context. This returns the rendered template - that is, it replaces template variables with the actual values of the variables, and it executes any template tags. 


Note that you did not order a warranty paragraph was displayed because the ordered_warranty variable evaluated to False. Also, note the date:  January 8, 2017 which was displayed according to the format string "F j, Y".

If you are new to Python, you may wonder why this output includes newline characters ("\n") rather than displaying line breaks. That is happening because of a subtlety in the Python interactive interpreter: the call to t.render(c) returns a string, and by default the interactive interpreter displays the representation  of the string, rather than the printed value of the string. If you want to see the string with line breaks displayed as true line breaks rather than "\n" characters, use the print function:
print t.render(c)

These are the fundamentals of using the Django template system: just write a template string, create a Template object, create a Context, and call the render method.


No comments:

Post a Comment