You are on page 1of 3

django_template_cheat.

txt
Page 1 of 3 Aug/2008
1 ######################Rendition of django html templates
2 from django.template import Context, Template
3 t = Template("My name is {{ my_name }}.")
4 c = Context({"my_name": "adrian"})
5 t.render(c) # outputs "My name is Adrian"
6 c = Context({"my_name": "dolores"})
7 t.render(c) # outputs "My name is dolores"
8
9 t = Template("My name is {{ person.first_name }}.")
10 # when render meets a "." it will first try person["first_name"]
11 c = Context({"person": {"first_name": "Joe", "last_name": "Johnson"}})
12 # then person.first_name
13 class PersonClass: pass
14 p = PersonClass()
15 p.first_name = "Joe"
16 c = Context({"person": p})
17 # then person.first_name()
18 class PersonClass2:
19 def first_name(self):
20 return "Joe"
21 p = PersonClass2()
22 c = Context({"person": p})
23 # then person[first_name]
24 c = Context({"person": ["Samantha", "Ron", "Joe"], 'first_name': 2})
25
26 c = Context({"name": "david"})
27 c['name']
28 del c['name']
29 c['name']="jack"
30
31 #often you want modules to automatically add some variables into your context:
32 from django.template import RequestContext
33 def extraProcessor(request):
34 return {'misc_extra_dictonary': 'here'}
35 c = RequestContext(request, {'name': 'david',}, extraProcessor)
36 #c will be populated with extra vars
37 #it will read the settings.py for TEMPLATE_CONTEXT_PROCESSORS and execute them all
38 #modules are under django.core.context_processors
39 #include auth:supporting users, debug, i18n, media, request:include request in context
40 #any function that takes a HttpRequest and returns a dictionary can be used
41
42 #often you want to load html pages:
43 from django.template.loader import get_template, select_template
44 t=get_template(template_name) #load file or exception
45 t=select_template(template_name_list) #load first in list that exists
46 #it will only load from TEMPLATE_DIRS in settings.py
47
48 #often you want to save time not doing all this context, template stuff:
49 from django.template.loader import render_to_string
50 rendered = render_to_string('my_template.html', { 'foo': 'bar' })
51
52 #often you want to write your own filters and tags
53 #but right now you don't know what filters and tags are yet....
54
55 ######################Sample page base_generic.html
56 {# this is a comment #}
57
58 {% load custom_module1 custom_module2 %}
59 {# loads custom python filter and tag modules#}
60
61 <html>
62 <head>
63 <link rel="stylesheet" href="style.css" />
64 <title>{% block title %}David Website{% endblock %}</title>
65 {# defining blocks will allow you to replace them later #}

- 1 -
django_template_cheat.txt
Page 2 of 3 Aug/2008
66 </head>
67 <body>
68 <div id="sidebar">
69 {% block sidebar %}
70 <ul>
71 <li><a href="/">Home</a></li>
72 <li><a href="/blog/">Blog</a></li>
73 </ul>
74 {% endblock %}
75 </div>
76
77 <div id="content">
78 {% block content %}{% endblock %}
79 </div>
80
81 <div id="disclaimer">
82 {% block disclaimer %}Copyright David{% endblock david %}
83 {% include "legals/extraDisclaimer.html" %}
84 {# renders that html into this page, passes current context #}
85 </div>
86
87 {% if wantDebug %}
88 {% debug %}{% enddebug %}
89 {% endif %}
90 </body>
91 </html>
92
93 ######################Sample page extended.html
94 {% extends "base_generic.html" %}
95 {# if you render this page, it will render the base_generic.html #}
96 {# with each block that is defined here replacing that of the parent #}
97
98 {% load custom_module2 %}
99 {# note that if your parent loads a module, you don't have it #}
100
101 {% block title %}{{ section.title }}{% endblock %}
102 {# replace the block called "title" in base_generic #}
103 {# reads variable called section from the context #}
104 {# searches section["title"],section.title,section.title(),section[title] #}
105 {# in that exact order #}
106
107 {# unreplaced blocks from base_generic.html, such as 'sidebar' are kept #}
108
109 {% block content %}
110 {% spaceless %} {# removes useless whitespace from the html below #}
111 <h1>{{ section.title }}</h1>
112 {% for story in story_list %}
113 <h2 color:{% cycle 'red' 'blue' %}>
114 {# each time the tag is read, it will output the next item #}
115 {{ forloop.counter }}
116 {# prints the loop counter #}
117 {# also: counter0, revcounter/0, first, last, parentloop.counter) #}
118 <a href="{{ story.get_absolute_url }}">
119 {{ story.headline|upper|capfirst }}
120 {# the filter uppercases then captalises first letter #}
121 </a>
122 </h2>
123 <p>{{ story.tease|cut:"\n"|truncatewords:"100" }}</p>
124 {# the filter removes \n and then gets first 100 words #}
125 {{ story.first_comment }}
126 {# by default the variable is escaped #}
127 {# < > ' " & are converted into html character codes #}
128
129 {{ story.comment_list|first }}
130 {{ story.comment_list|join:", "}}

- 2 -
django_template_cheat.txt
Page 3 of 3 Aug/2008
131
132 {{ story.special_comment|default:"No Special Comments!" }}
133 {# if story.special_comment evaluates to false, return default value #}
134
135 {{ story.first_html_comment|safe }}
136 {# turn off auto escaping #}
137
138 {{ story.file_size|filesizeformat }}
139 {# uses b, kb, mb, gb instead of big numbers #}
140 {% endfor %}
141 There are {{ story_list|length }} comment{{ story_list|length|pluralize }}
142 {# will return 's', or nothing. can pass string for different suffix #}
143
144 {% endspaceless %}
145 {% endblock %}
146
147 {% block disclaimer %}
148 {% if section.author %}
149 {# executes when: condition exists, not empty and not false #}
150 {{ block.super }} and also Copyright {{ section.author }}
151 {# block.super retrieves what the parent would look like #}
152 {% else %} {# otherwise execute this bit #}
153 {{ block.super }} and nobody else at all!!!
154 {% endif %}
155 <br>
156 Contributors: <br>
157 {% regroup people by gender as gender_list %}
158 {# people is a dictionary, 'gender' is a key #}
159 {# 'gender_list' will be all elements of people grouped by 'gender' #}
160 {% for gender in gender_list %}
161 {{ gender.grouper }}:
162 {# this is the group: either 'male' or 'female' in this example #}
163 {% for person in gender.list %}
164 {{ person.name }},
165 {% endfor %}<br>
166 {% endfor %}
167
168 {% endblock disclaimer %}
169
170 {% comment %}
171 Multiline Comment!!!!
172 In the Regroup example, the context had people described below:
173 people = [
174 {'name': 'Bill', 'gender': 'Male'},
175 {'name': 'Pat', 'gender': 'Female'},
176 {'name': 'Margaret', 'gender': 'Female'},
177 ]
178 then it would output
179 Female: Pat, Margaret
180 Male: Bill
181 {% endcomment %}
182
183 ######################Reference of Tags {% tag %} xxxx {% endtag %}
184 autoescape, block, comment, cycle, debug, extends, filter, firstof,
185 for, if, ifchanged, ifequal, ifnotequal, include, load, now, regroup,
186 spaceless, ssi, templatetag, url, widthratio, with
187
188 ######################Reference of Filters {{ var|filter1|filter2 }}
189 add, addslashes, capfirst, center, cut, date, default, default_if_none, dictsort,
190 dictsortreversed, divisibleby, escape, escapejs, filesizeformat, first, fix_ampersands,
191 floatformat, force_escape, get_digit, iriencode, join, last, length, length_is,
192 linebreaks, linebreaksbr, linenumbers, ljust, lower, make_list, phone2numeric, pluralize,
193 pprint, random, removetags, rjust, safe, slice, slugify, stringformat, striptags, time,
194 timesince, timeuntil, title, truncatewords, truncatewords_html, unordered_list, upper,
195 urlencode, urlize, urlizetrunc, wordcount, wordwrap, yesno

- 3 -