A single tag is normally sufficient when it comes to template based operations.
However, sometimes you'll need to capture the contents of the template before choosing what to do with it.
For example, the built-in template tag "if" and "endif".
The tag captures anything between the if/endif tags and then does something with it.
The example below is straight from Django docs.
1.
{
%
upper
%
}{{ name }} will appear
in
uppercase.{
%
endupper
%
}
The usage of the template tag seems simple enough. Uppercase all the text between the tags.
The creation of the custom tag is below.
01.
def
do_upper(parser, token):
02.
nodelist
=
parser.parse((
'endupper'
,))
03.
parser.delete_first_token()
04.
05.
return
UpperNode(nodelist)
06.
07.
class
UpperNode(template.Node):
08.
def
__init__(
self
, nodelist):
09.
self
.nodelist
=
nodelist
10.
11.
def
render(
self
, context):
12.
output
=
self
.nodelist.render(context)
13.
return
output.upper()
The magic line there is self.nodelist.render(context), which pulls out all the content in between and renders it properly before performing the upper-casing operation.
[ Source ]