django_template_cheat.txt Page 1 of 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
Aug/2008
######################Rendition of django html templates django . template import Context, Context , Template from django. t = Template( Template ( "My name is {{ my_name }}.") }}.") c = Context({ Context ({ "my_name" "my_name": : "adrian" "adrian"}) }) t . render( render ( c ) # outputs "My name is Adrian" c = Context({ Context ({ "my_name" "my_name": : "dolores" "dolores"}) }) t . render( render ( c ) # outputs "My name is dolores" t = Template( Template ( "My name is {{ person.first_name }}.") }}.") # when render meets a "." it will first try person["first_name"] c = Context({ Context ({ "person" "person": : { "first_name" "first_name": : "Joe" "Joe", , "last_name" "last_name": : "Johnson" "Johnson"}} }} ) # then person.first_name PersonClass: : pass class PersonClass p = PersonClass() PersonClass () p . first_name = "Joe" c = Context({ Context ({ "person" "person": : p }) # then person.first_name() PersonClass2: : class PersonClass2 de f first_name first_name( ( self): self ): return "Joe" p = PersonClass2() PersonClass2() c = Context({ Context ({ "person" "person": : p }) # then person[first_name] c = Context({ Context ({ "person" "person": : [ "Samantha" "Samantha", , "Ron" "Ron", , "Joe" "Joe"], ], 'first_name' 'first_name': : 2 }) c = Context({ Context ({ "name" "name": : "david" "david"}) }) c [ 'name' 'name'] ] 'name'] ] de l c [ 'name' c [ 'name' 'name']= ]= "jack" #often you want modules to automatically add some variables into your context: django . template import RequestContext from django. extraProcessor( ( request): request ): de f extraProcessor return { 'misc_extra_dictonary' 'misc_extra_dictonary': : 'here' 'here'} } c = RequestContext( RequestContext( request, request , { 'name' 'name': : 'david' 'david',} ,} , extraProcessor) extraProcessor) #c will be populated with extra vars #it will read the settings.py for TEMPLATE_CONTEXT_PROCESSORS and execute them all #modules are under django.core.context_processors #include auth:supporting users, debug, i18n, media, request:include request in context #any function that takes a HttpRequest HttpRequest and returns a dictionary can be used #often you want to load html pages: from django. django . template. template . loader import get_template, get_template, select_template t = get_template( get_template ( template_name) template_name ) #load file or exception t = select_template( select_template ( template_name_list template_name_list) ) #load first in list that exists #it will only load from TEMPLATE_DIRS in settings.py #often you want to save time not doing all this context, template stuff: from django. django . template. template . loader import render_to_string rendered = render_to_string( render_to_string ( 'my_template.html' 'my_template.html', , { 'foo' 'foo': : 'bar' }) #often you want to write your own filters and tags #but right now you don't know what filters and tags are yet.... ######################Sample page base_generic.html { # this is a comment #} {% load custom_module1 custom_module2 %} { # loads custom python filter and tag modules#} < html> html > < head> head > < link rel= rel= "stylesheet" href= href = "style.css" /> < title>{ title >{ % block title %} David Website{% Website{% endblock %} %} > { # defining blocks will allow you to replace them later #} - 1 -
django_template_cheat.txt Page 2 of 3 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
Aug/2008
head> head > < body> body > < div id= id= "sidebar" "sidebar"> > {% block sidebar %} < ul > < li >< a href= href= "/ " > Home Home a >< / li > < li >< a href= href= "/blog/" "/blog/"> > Blog Blog a >< / li > ul > {% endblock %} di v > < div id= id= "content" "content"> > {% block content %}{% endblock %} di v > < div id= id= "disclaimer" "disclaimer"> > {% block disclaimer %} Copyright David{% David{% endblock david %} {% include "legals/extraDisclaimer.html" %} { # renders that html into this page, passes current context #} di v > {% if wantDebug %} {% debug %}{% enddebug %} {% endif %} body> body > html> html > ######################Sample page extended.html {% extends "base_generic.html" %} { # if you render this page, it will render the base_generic.html #} { # with each block that is defined here replacing that of the parent #} {% load custom_module2 %} { # note that if your parent loads a module, you don't have it #} {% {# {# {# {#
block title %}{{ section. section . title }}{% endblock %} replace the block called "title" in base_generic #} reads variable called section from the context #} searches section["title"],section.title,section.title(),section[title] #} in that exact order #}
{ # unreplaced blocks from base_generic.html, such as 'sidebar' are kept #} {% block content %} {% spaceless %} { # removes useless whitespace from the html below #} < h1 >{ { section. section . title }} }} {% fo r story in story_list %} < h2 color:{ color :{ % cycle 'red' 'blue' %} > { # each time the tag is read, it will output the next item #} {{ forloop. forloop . counter }} { # prints the loop counter #} { # also: counter0, revcounter/0, first, last, parentloop.counter) #} < a href= href= "{{ story.get_absolute_url }}"> }}"> {{ story. story . headline| headline | upper| upper | capfirst }} { # the filter uppercases then captalises first letter #} a > h2 > < p >{ { story. story . tease| tease | cu t : "\n" "\n"| | truncatewords: truncatewords : "100" }} }} { # the filter removes \n and then gets first 100 words #} {{ story. story . first_comment }} { # by default the variable is escaped #} {# < > ' " & are converted into html character codes #} {{ story. story . comment_list| comment_list| first }} {{ story. story . comment_list| comment_list| join: join : ", " }} - 2 -
django_template_cheat.txt Page 3 of 3 131 132 133 134 135 136 137 138 139 140 141 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 171 172 172 173 174 175 176 177 178 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
Aug/2008
{{ story. story . special_comment| special_comment| default: default : "No Special Comments!" }} { # if story.special_comment evaluates to false, return default value #} {{ story. story . first_html_comment first_html_comment| | safe }} { # turn off auto escaping #} {{ story. story . file_size| file_size| filesizeformat }} { # uses b, kb, mb, gb instead of big numbers #} {% endfor %} There are {{ story_list| story_list | length }} comment{{ comment {{ story_list| story_list | length| length | pluralize }} { # will return 's', or nothing. can pass string for different suffix #} {% endspaceless %} {% endblock %} {% block disclaimer %} {% if section. section . author %} { # executes when: condition exists, not empty and not false #} {{ block. block . super }} an d also Copyright {{ section. section . author }} { # block.super retrieves what the parent would look like #} {% else %} { # otherwise execute this bit #} {{ block. block . super }} an d nobody else at all!! all!! ! {% endif %} < br > Contributors: Contributors: < br > {% regroup people by gender as gender_list %} { # people is a dictionary, 'gender' is a key #} { # 'gender_list' will be all elements of people grouped by 'gender' #} {% fo r gender in gender_list %} {{ gender. gender . grouper }} : { # this is the group: either 'male' or 'female' in this example #} {% fo r person in gender. gender . list %} {{ person. person . name }} , {% endfor %} < br > {% endfor %} {% endblock disclaimer %} {% comment %} Multiline Comment!!!! Comment!!!! In the Regroup example, example, the context had people described below: below: people = [ { 'name' 'name': : 'Bill' 'Bill', , 'gender' 'gender': : 'Male' 'Male'}, }, { 'name' 'name': : 'Pat' 'Pat', , 'gender' 'gender': : 'Female' 'Female'}, }, { 'name' 'name': : 'Margaret' 'Margaret', , 'gender' 'gender': : 'Female' 'Female'}, }, ] then it would output Female: Female: Pa t , Margaret Male: Male : Bill {% endcomment %} ######################Reference of Tags {% tag %} xxxx {% endtag %} autoescape, autoescape, block, block , comment, comment , cycle, cycle , debug, debug , extends, extends , filter, filter , firstof, firstof , fo r , if , ifchanged, ifchanged , ifequal, ifequal , ifnotequal, ifnotequal , include, include , load, load , no w , regroup, regroup , spaceless, spaceless, ss i , templatetag, templatetag , ur l , widthratio, widthratio , with ######################Reference of Filters {{ var|filter1|filter2 }} add, add , addslashes, addslashes , capfirst, capfirst , center, center , cu t , date, date , default, default , default_if_none, default_if_none, dictsort, dictsort , dictsortreversed, divisibleby, dictsortreversed, divisibleby , escape, escape , escapejs, escapejs , filesizeformat, filesizeformat, first, first , fix_ampersands, fix_ampersands, floatformat, floatformat, force_escape, force_escape, get_digit, get_digit , iriencode, iriencode , join, join , last, last , length, length , length_is, length_is , linebreaks, linebreaks, linebreaksbr, linebreaksbr, linenumbers, linenumbers , ljust, ljust , lower, lower , make_list, make_list , phone2numeric, phone2numeric , pluralize, pluralize , pprint, pprint, random, random , removetags, removetags , rjust, rjust , safe, safe , slice, slice , slugify, slugify , stringformat, stringformat , striptags, striptags , time, time , timesince, timesince, timeuntil, timeuntil , title, title , truncatewords, truncatewords , truncatewords_html truncatewords_html, , unordered_list, unordered_list, upper, upper , urlencode, urlencode, urlize, urlize , urlizetrunc, urlizetrunc , wordcount, wordcount , wordwrap, wordwrap , yesno - 3 -