0% found this document useful (0 votes)
19 views

Module 2notes

Uploaded by

sabeeltanveer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module 2notes

Uploaded by

sabeeltanveer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Module 2

2.1 The Django Template System


A Django template is a string of text that is intended to separate the presentation of a
document from its data. A template defines placeholders and various bits of basic logic (i.e.,
template tags) that regulate how the document should be displayed.

Example: The template describes an HTML page that thanks a person for placing an order with
a company.
 Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable. This
means “insert the value of the variable with the given name.
 Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_
warranty %}) is a template tag.
 This example template contains two tags: the {% for item in item_list %} tag (a for tag)
and the {% if ordered_warranty %} tag (an if tag).
 Finally, the second paragraph of this template has an example of a filter, with which you
can alter the display of a variable. In this example, {{ ship_date|date:"F j, Y" }}, we’re
passing the ship_date variable to the date filter, giving the date filter the argument "F j,
Y". The date filter formats dates in a given format, as specified by that argument. Filters
are attached using a pipe character (|), as a reference to Unix pipes

2.2 Using the Template System


To use the template system in Python code, just follow these two steps:

1. Create a Template object by providing the raw template code as a string. Django also offers a
way to create Template objects by designating the path to a template file on the filesystem;

2. Call the render() method of the Template object with a given set of variables (i.e., the context).
This returns a fully rendered template as a string, with all of the variables and block tags
evaluated according to the context.

2.3 Creating Template Objects


The Template class lives in the django.template module, and the constructor takes one argument,
the raw template code.

This constructor takes one argument - raw template code. There are three formats to define
template objects discussed below.

1. Three greater symbol (>>>) - designate the interactive interpreter’s prompt

2. Three dot (…)- multiple statements these are inserted by the python shell and are not part of
input.

3. Triple quote (”””) - marks to designate the string, because it wraps over multiple lines.
2.4 TemplateSyntaxError:
from django.template import Template

t = Template('{% notatag %} ')

Traceback (most recent call last):

File "<stdin>", line 1, in ?

The system raises a TemplateSyntaxError exception for any of the following cases:

• Invalid block tags

• Invalid arguments to valid block tags

• Invalid filters

• Invalid arguments to valid filters

• Invalid template syntax

• Unclosed block tags (for block tags that require closing tags)

2.5 Rendering a Template

 A context is simply a set of variables and their associated values. A template


uses this to populate its variable tags and evaluate its block tags.
 A context is represented in Django by the Context class, which lives in the
django.template module. Its constructor takes one optional argument: a
dictionary mapping variable names to variable values.
 Call the Template object’s render() method with the context to “fill” the
template:
from django.template import Context, Template
t = Template("My name is {{ name }}.")
c = Context({"name": "Stephane"})
t.render(c)
Output: 'My name is Stephane.'

To write a template, create a Template object, create a Context, and call the
render() method

Output:
Let’s step through this code one statement at a time:

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

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

• 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 block tags. The warranty paragraph was displayed because the
ordered_warranty variable evaluated to True. Also note the date, April 2, 2009, which is
displayed according to the format string 'F j, Y'.

2.6 Multiple Contexts, Same Template


Once you have a Template object, you can render multiple contexts through it.

Example:

It’s more efficient to create the Template object once, and then call render() on it multiple times:

Example:
2.7 Context Variable Lookup:
• The template system elegantly handles more complex data structures, such as lists,
dictionaries, and custom objects.
• The key to traversing complex data structures in Django templates is the dot character (.).
Use a dot to access dictionary keys, attributes, indices, or methods of an object.

There are four context variable lookup.

1. Dictionary lookup (e.g., foo["bar"])


2. Attribute lookup (e.g., foo.bar)
3. Method call (e.g., foo.bar())
4. List-index lookup (e.g., foo[bar]

1.Dictionary lookup: Passing a Python dictionary to a template. To access the values of that
dictionary by dictionary key, use a doT(.):

Output: 'Sally is 43 years old.'

2. Attribute lookup:(.) dots also allow access of object attributes.

Example: A Python datetime.date object has year, month, and day attributes, and you can use a
dot to access those attributes in a Django template.
Output: 'The month is 5 and the year is 1993.'

3. Method call: (.)Dots are also used to call methods on objects.

Example: Each Python string has the methods upper() and isdigit(), and you can call those in
Django templates using the same dot syntax:

4. List-index lookup:( .) dots are also used to access list indices. Negative list indices are not allowed.

Example:

Output: 'Item 2 is carrots.'

Dot lookups can be nested multiple levels deep.

Example: The following example uses {{ person.name.upper }}, which translates into a
dictionary lookup (person['name']) and then a method call (upper())
from django.template import Template, Context

person = {'name': 'Sally', 'age': '43'}

t = Template('{{ person.name.upper }} is {{ person.age }} years old.')

c = Context({'person': person})

t.render(c)

Output: 'SALLY is 43 years old.'

2.8 Basic Template Tags and Filters


Tags: Few tags are

1. if/else
2. for
3. ifequal/ifnotequal
4. comments

1. if/else: The {% if %} tag evaluates a variable, and if that variable is “true, the system will
display everything between {% if %} and {% endif %}.

Example:

If /else tag for multiple variables:

Example

You might also like