5. 1. Create a Template object by providing the raw
template code as a string.
2. Call the render() method of the Template object
with a given set of variables (the context). This
returns a fully rendered template as a string,
with all of the variables and template tags
evaluated according to the context.
6. Creating Template Objects
The easiest way to create a Template object is to
instantiate it directly. Running python manage.py shell
instead of just python.
The system raises a TemplateSyntaxError exception for
any of the following cases:
Invalid tags
Invalid arguments to valid tags
Invalid filters
Invalid arguments to valid filters
Invalid template syntax
Unclosed tags (for tags that require closing tags)
10. • Method Call Behavior
• If, during the method lookup, a method raises an exception,
the exception will be propagated, unless the exception has
an attribute silent_variable_failure whose value is True. If
the exception does have a silent_variable_failure attribute,
the variable will render as an empty string.
• A method call will only work if the method has no required
arguments. Otherwise, the system will move to the next
lookup type (list-index lookup).
• Some methods have side effects, and it would be foolish at
best, and possibly even a security hole, to allow the
template system to access them.
• How Invalid Variables Are Handled
• If a variable doesn’t exist, the template system renders it as
an empty string, failing silently.
11. Playing with Context Objects
A context is simply a set of template variable names
and their associated values.
Most of the time, you’ll instantiate Context objects
by passing in a fully populated dictionary to
Context(). But you can add and delete items from a
Context object once it’s been instantiated, too,
13. Tag
• if / else
And, Or, Not, elif
• for
forloop.counter
forloop.counter0
forloop.revcounter
forloop.revcounter0
forloop.first
forloop.last
forloop.parentloop
• ifequal / ifnotequal
• comments
Invalid examples
14. An empty list ([])
An empty tuple (())
An empty dictionary ({})
An empty string ('')
Zero (0)
The special object None
The object False (obviously)
Custom objects that define their own Boolean context
behavior (this is advanced Python usage)
False in a Boolean context
15. Filter
• {{ name|lower }}:Do not put any space character
before and after the pipe.
• {{ my_list|first|upper }}:Filters can be chained.
• {{ bio|truncatewords:"30" }}:Double quotes only.
• {{ pub_date|date:"F j, Y" }}
19. 1. Create a base.html template that holds the main
look and feel of your site.
2. Create a base_SECTION.html template for each
“section” of your site (e.g., base_photos.html
and base_forum.html).
3. Create individual templates for each type of
page, such as a forum page or a photo gallery.
Template Inheritance