-
Notifications
You must be signed in to change notification settings - Fork 0
Chapter 3 Templates
Django Templating Language
Jinja
##Expressing a Template
from django import template
t = template.Template('{{a}}, {{b}} ,3 ,4')
c = template.Context({'a':1,'b':2})
result = t.render(c)
print(result)
1,2,3,4
##Ref methods of object
NOTE: you can only call methods that do not take an arg
from django import template
t = template.Template('{{ a.isupper }}')
c = template.Context({'a': 'TEST'})
print(t.render(c))
TRUE
##Ref attribute of object
class Person(object):
def init(self,sex,name):
self.sex = sex
self.name = name
bob = Person('male','Jason')
t = template.Template('{{human.name}} is a {{human.sex}}')
c = template.Context({'human': bob})
print(t.render(c))
"Jason is a male"
##Index of a list
t = template.Template('Item number 2 is {{items.1}}')
c = template.Context({'items':['grapes','hamburger','cheese']})
print(t.render(c))
Item number 2 is hamburger
For complex data structures you can use . notation. With this you can access
- dict keys
- atrributes
- methods
- indices of object
- object attributes
if tags accept and,or,and not however they do not accept parenthesis to order priority
'{% if expression }%
{%elif expression%}
{%else%}
{%endif%}'
{%for item in item_list%}
{%empty%} what to do if item_list is empty {%endfor%}
forloop.counter = variable ref the current num of loops. one-indexed forloop.revcounter = ref the remaining # of loops till end. last loop=1 forloop.first and forloop.last = Bool for first or last loop
##Filters
filters are functions. they are applied to a variable with the | command. if there are args they come after a :
lower = convert str to lower case
addslashes = adds a backslash before any backslash,single quote, or double quote. useful for escaping
date = formats a date or datetime object
length = length of object
##Template Loading
in the Settings.py there are some control variables for templates:
Backend = which template language to use DIRS = list of directories where the engine should look for templates APP_DIRS = should engine look for templates inside installed apps
get_template() is a providing function that can be used to load a template by name. it locates the templates first based on App template folders then by any entries in the DIR.
to use get_template(): from django.template.loaders import get_template
render() is a django shortcut to do all these in one line from django.shortcuts import render render(http request,template name,Dict)
##The include tag## allows an import of a template into this template