- 自定义模板(template)的标签(tags)和过滤器(filters)
- Code layout
- 编写自定义的模板过滤器
- Writing custom template tags
- Simple tags
- Inclusion tags
- Advanced custom template tags
- A quick overview
- Writing the compilation function
- Writing the renderer
- 自动转义的注意事项
- Thread-safety considerations
- Registering the tag
- Passing template variables to the tag
- Setting a variable in the context
- Parsing until another block tag
- Parsing until another block tag, and saving contents
自定义模板(template)的标签(tags)和过滤器(filters)
Django's template language comes with a wide variety of built-intags and filters designed to address thepresentation logic needs of your application. Nevertheless, you mayfind yourself needing functionality that is not covered by the coreset of template primitives. You can extend the template engine bydefining custom tags and filters using Python, and then make themavailable to your templates using the {% load %}
tag.
Code layout
The most common place to specify custom template tags and filters is insidea Django app. If they relate to an existing app, it makes sense to bundle themthere; otherwise, they can be added to a new app. When a Django app is addedto INSTALLED_APPS
, any tags it defines in the conventional locationdescribed below are automatically made available to load within templates.
The app should contain a templatetags
directory, at the same level asmodels.py
, views.py
, etc. If this doesn't already exist, create it -don't forget the init.py
file to ensure the directory is treated as aPython package.
开发服务器并不会自动重启
After adding the templatetags
module, you will need to restart yourserver before you can use the tags or filters in templates.
Your custom tags and filters will live in a module inside the templatetags
directory. The name of the module file is the name you'll use to load the tagslater, so be careful to pick a name that won't clash with custom tags andfilters in another app.
For example, if your custom tags/filters are in a file calledpoll_extras.py
, your app layout might look like this:
- polls/
- __init__.py
- models.py
- templatetags/
- __init__.py
- poll_extras.py
- views.py
And in your template you would use the following:
- {% load poll_extras %}
The app that contains the custom tags must be in INSTALLED_APPS
inorder for the {% load %}
tag to work. This is a security feature:It allows you to host Python code for many template libraries on a single hostmachine without enabling access to all of them for every Django installation.
There's no limit on how many modules you put in the templatetags
package.Just keep in mind that a {% load %}
statement will loadtags/filters for the given Python module name, not the name of the app.
To be a valid tag library, the module must contain a module-level variablenamed register
that is a template.Library
instance, in which all thetags and filters are registered. So, near the top of your module, put thefollowing:
- from django import template
- register = template.Library()
Alternatively, template tag modules can be registered through the'libraries'
argument toDjangoTemplates
. This is useful ifyou want to use a different label from the template tag module name whenloading template tags. It also enables you to register tags without installingan application.
Behind the scenes
For a ton of examples, read the source code for Django's default filtersand tags. They're in django/template/defaultfilters.py
anddjango/template/defaulttags.py
, respectively.
For more information on the load
tag, read its documentation.
编写自定义的模板过滤器
自定义的过滤器就是一些有一到两个参数的Python函数
- (输入的)变量的值,不一定得是字符串类型
- 而参数的值,它们可以有一个默认值,或者被排除在外
举个例子,在过滤器{{ var|foo:"bar" }}
中,变量var
和参数bar
会传递给过滤器foo
因为模板语言不提供异常处理机制,所以任何从模板过滤器中抛出的异常都将被视为服务器异常。因此,如果有一个合理的返回值将要被返回的话,过滤器函数应当避免产生异常。万一模板中出现有明显错误的输入,产生异常也仍然比隐藏这个bug要好。
这是一个过滤器定义的例子:
- def cut(value, arg):
- """Removes all values of arg from the given string"""
- return value.replace(arg, '')
这个例子展示了如何使用这个过滤器:
- {{ somevariable|cut:"0" }}
大部分的过滤器并没有参数。这样的话,只需要把这些参数从你的函数中去掉就好。例子如下:
- def lower(value): # Only one argument.
- """Converts a string into all lowercase"""
- return value.lower()
注册自定义过滤器
- register.filter('cut', cut)
- register.filter('lower', lower)
``Library.filter()``方法有两个参数:
- 筛选器的名称——字符串。
- The compilation function — a Python function (not the name of thefunction as a string).
You can useregister.filter()
as a decorator instead:
If you leave off the name
argument, as in the second example above, Djangowill use the function's name as the filter name.
Finally, register.filter()
also accepts three keyword arguments,is_safe
, needs_autoescape
, and expects_localtime
. These argumentsare described in filters and auto-escaping andfilters and time zones below.
Template filters that expect strings
django.template.defaultfilters.
stringfilter
()- If you're writing a template filter that only expects a string as the firstargument, you should use the decorator
stringfilter
. This willconvert an object to its string value before being passed to your function:
- from django import template
- from django.template.defaultfilters import stringfilter
- register = template.Library()
- @register.filter
- @stringfilter
- def lower(value):
- return value.lower()
This way, you'll be able to pass, say, an integer to this filter, and itwon't cause an AttributeError
(because integers don't have lower()
methods).
筛选器和自动转义
When writing a custom filter, give some thought to how the filter will interactwith Django's auto-escaping behavior. Note that two types of strings can bepassed around inside the template code:
Raw strings are the native Python strings. On output, they're escaped ifauto-escaping is in effect and presented unchanged, otherwise.
Safe strings are strings that have been marked safe from furtherescaping at output time. Any necessary escaping has already been done.They're commonly used for output that contains raw HTML that is intendedto be interpreted as-is on the client side.
Internally, these strings are of typeSafeText
. You can test for themusing code like:
- from django.utils.safestring import SafeText
- if isinstance(value, SafeText):
- # Do something with the "safe" string.
- ...
Template filter code falls into one of two situations:
- Your filter does not introduce any HTML-unsafe characters (
<
,>
,'
,"
or&
) into the result that were not already present. Inthis case, you can let Django take care of all the auto-escapinghandling for you. All you need to do is set theis_safe
flag toTrue
when you register your filter function, like so:
- @register.filter(is_safe=True)
def myfilter(value):
return value
This flag tells Django that if a "safe" string is passed into yourfilter, the result will still be "safe" and if a non-safe string ispassed in, Django will automatically escape it, if necessary.
You can think of this as meaning "this filter is safe — it doesn'tintroduce any possibility of unsafe HTML."
The reason is_safe
is necessary is because there are plenty ofnormal string operations that will turn a SafeData
object back intoa normal str
object and, rather than try to catch them all, which wouldbe very difficult, Django repairs the damage after the filter has completed.
For example, suppose you have a filter that adds the string xx
tothe end of any input. Since this introduces no dangerous HTML charactersto the result (aside from any that were already present), you shouldmark your filter with is_safe
:
- @register.filter(is_safe=True)
def add_xx(value):
return '%sxx' % value
When this filter is used in a template where auto-escaping is enabled,Django will escape the output whenever the input is not already markedas "safe".
By default, is_safe
is False
, and you can omit it from any filterswhere it isn't required.
Be careful when deciding if your filter really does leave safe stringsas safe. If you're removing characters, you might inadvertently leaveunbalanced HTML tags or entities in the result. For example, removing a>
from the input might turn <a>
into <a
, which would need tobe escaped on output to avoid causing problems. Similarly, removing asemicolon (;
) can turn &
into &
, which is no longer avalid entity and thus needs further escaping. Most cases won't be nearlythis tricky, but keep an eye out for any problems like that whenreviewing your code.
Marking a filter is_safe
will coerce the filter's return value toa string. If your filter should return a boolean or other non-stringvalue, marking it is_safe
will probably have unintendedconsequences (such as converting a boolean False to the string'False').
- Alternatively, your filter code can manually take care of any necessaryescaping. This is necessary when you're introducing new HTML markup intothe result. You want to mark the output as safe from furtherescaping so that your HTML markup isn't escaped further, so you'll needto handle the input yourself.
To mark the output as a safe string, usedjango.utils.safestring.mark_safe()
.
Be careful, though. You need to do more than just mark the output assafe. You need to ensure it really is safe, and what you do depends onwhether auto-escaping is in effect. The idea is to write filters thatcan operate in templates where auto-escaping is either on or off inorder to make things easier for your template authors.
In order for your filter to know the current auto-escaping state, set theneeds_autoescape
flag to True
when you register your filter function.(If you don't specify this flag, it defaults to False
). This flag tellsDjango that your filter function wants to be passed an extra keywordargument, called autoescape
, that is True
if auto-escaping is ineffect and False
otherwise. It is recommended to set the default of theautoescape
parameter to True
, so that if you call the functionfrom Python code it will have escaping enabled by default.
For example, let's write a filter that emphasizes the first character ofa string:
- from django import template
- from django.utils.html import conditional_escape
- from django.utils.safestring import mark_safe
- register = template.Library()
- @register.filter(needs_autoescape=True)
- def initial_letter_filter(text, autoescape=True):
- first, other = text[0], text[1:]
- if autoescape:
- esc = conditional_escape
- else:
- esc = lambda x: x
- result = '<strong>%s</strong>%s' % (esc(first), esc(other))
- return mark_safe(result)
The needs_autoescape
flag and the autoescape
keyword argument meanthat our function will know whether automatic escaping is in effect when thefilter is called. We use autoescape
to decide whether the input dataneeds to be passed through django.utils.html.conditional_escape
or not.(In the latter case, we just use the identity function as the "escape"function.) The conditional_escape()
function is like escape()
exceptit only escapes input that is not a SafeData
instance. If aSafeData
instance is passed to conditional_escape()
, the data isreturned unchanged.
Finally, in the above example, we remember to mark the result as safeso that our HTML is inserted directly into the template without furtherescaping.
There's no need to worry about the is_safe
flag in this case(although including it wouldn't hurt anything). Whenever you manuallyhandle the auto-escaping issues and return a safe string, theis_safe
flag won't change anything either way.
警告
Avoiding XSS vulnerabilities when reusing built-in filters
Django's built-in filters have autoescape=True
by default in order toget the proper autoescaping behavior and avoid a cross-site scriptvulnerability.
In older versions of Django, be careful when reusing Django's built-infilters as autoescape
defaults to None
. You'll need to passautoescape=True
to get autoescaping.
For example, if you wanted to write a custom filter calledurlize_and_linebreaks
that combined the urlize
andlinebreaksbr
filters, the filter would look like:
- from django.template.defaultfilters import linebreaksbr, urlize
- @register.filter(needs_autoescape=True)
- def urlize_and_linebreaks(text, autoescape=True):
- return linebreaksbr(
- urlize(text, autoescape=autoescape),
- autoescape=autoescape
- )
接下来:
- {{ comment|urlize_and_linebreaks }}
would be equivalent to:
- {{ comment|urlize|linebreaksbr }}
过滤器和时区
If you write a custom filter that operates on datetime
objects, you'll usually register it with the expects_localtime
flag set toTrue
:
- @register.filter(expects_localtime=True)
def businesshours(value):
try:
return 9 <= value.hour < 17
except AttributeError:
return ''
When this flag is set, if the first argument to your filter is a time zoneaware datetime, Django will convert it to the current time zone before passingit to your filter when appropriate, according to rules for time zonesconversions in templates.
Writing custom template tags
Tags are more complex than filters, because tags can do anything. Djangoprovides a number of shortcuts that make writing most types of tags easier.First we'll explore those shortcuts, then explain how to write a tag fromscratch for those cases when the shortcuts aren't powerful enough.
Simple tags
django.template.Library.
simple_tag
()- Many template tags take a number of arguments — strings or template variables— and return a result after doing some processing based solely onthe input arguments and some external information. For example, a
current_time
tag might accept a format string and return the time as astring formatted accordingly.
To ease the creation of these types of tags, Django provides a helper function,simple_tag
. This function, which is a method ofdjango.template.Library
, takes a function that accepts any number ofarguments, wraps it in a render
function and the other necessary bitsmentioned above and registers it with the template system.
Our current_time
function could thus be written like this:
- import datetime
- from django import template
- register = template.Library()
- @register.simple_tag
- def current_time(format_string):
- return datetime.datetime.now().strftime(format_string)
A few things to note about the simple_tag
helper function:
- Checking for the required number of arguments, etc., has already beendone by the time our function is called, so we don't need to do that.
- The quotes around the argument (if any) have already been stripped away,so we just receive a plain string.
- If the argument was a template variable, our function is passed thecurrent value of the variable, not the variable itself.
Unlike other tag utilities,simple_tag
passes its output throughconditional_escape()
if the template context is inautoescape mode, to ensure correct HTML and protect you from XSSvulnerabilities.
If additional escaping is not desired, you will need to usemark_safe()
if you are absolutely sure that yourcode does not contain XSS vulnerabilities. For building small HTML snippets,use of format_html()
instead of mark_safe()
isstrongly recommended.
If your template tag needs to access the current context, you can use thetakes_context
argument when registering your tag:
- @register.simple_tag(takes_context=True)
def current_time(context, format_string):
timezone = context['timezone']
return your_get_current_time_method(timezone, format_string)
Note that the first argument must be called context
.
For more information on how the takes_context
option works, see the sectionon inclusion tags.
If you need to rename your tag, you can provide a custom name for it:
- register.simple_tag(lambda x: x - 1, name='minusone')
- @register.simple_tag(name='minustwo')
- def some_function(value):
- return value - 2
simple_tag
functions may accept any number of positional or keywordarguments. For example:
- @register.simple_tag
def my_tag(a, b, args, *kwargs):
warning = kwargs['warning']
profile = kwargs['profile']
…
return …
Then in the template any number of arguments, separated by spaces, may bepassed to the template tag. Like in Python, the values for keyword argumentsare set using the equal sign ("=
") and must be provided after thepositional arguments. For example:
- {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
It's possible to store the tag results in a template variable rather thandirectly outputting it. This is done by using the as
argument followed bythe variable name. Doing so enables you to output the content yourself whereyou see fit:
- {% current_time "%Y-%m-%d %I:%M %p" as the_time %}
- <p>The time is {{ the_time }}.</p>
Inclusion tags
django.template.Library.
inclusion_tag
()- Another common type of template tag is the type that displays some data byrendering another template. For example, Django's admin interface uses customtemplate tags to display the buttons along the bottom of the "add/change" formpages. Those buttons always look the same, but the link targets changedepending on the object being edited — so they're a perfect case for using asmall template that is filled with details from the current object. (In theadmin's case, this is the
submit_row
tag.)
These sorts of tags are called "inclusion tags".
Writing inclusion tags is probably best demonstrated by example. Let's write atag that outputs a list of choices for a given Poll
object, such as wascreated in the tutorials. We'll use the tag like this:
- {% show_results poll %}
…and the output will be something like this:
- <ul>
- <li>First choice</li>
- <li>Second choice</li>
- <li>Third choice</li>
- </ul>
First, define the function that takes the argument and produces a dictionary ofdata for the result. The important point here is we only need to return adictionary, not anything more complex. This will be used as a template contextfor the template fragment. Example:
- def show_results(poll):
- choices = poll.choice_set.all()
- return {'choices': choices}
Next, create the template used to render the tag's output. This template is afixed feature of the tag: the tag writer specifies it, not the templatedesigner. Following our example, the template is very simple:
- <ul>
- {% for choice in choices %}
- <li> {{ choice }} </li>
- {% endfor %}
- </ul>
Now, create and register the inclusion tag by calling the inclusion_tag()
method on a Library
object. Following our example, if the above template isin a file called results.html
in a directory that's searched by thetemplate loader, we'd register the tag like this:
- # Here, register is a django.template.Library instance, as before
- @register.inclusion_tag('results.html')
- def show_results(poll):
- ...
Alternatively it is possible to register the inclusion tag using adjango.template.Template
instance:
- from django.template.loader import get_template
- t = get_template('results.html')
- register.inclusion_tag(t)(show_results)
…when first creating the function.
Sometimes, your inclusion tags might require a large number of arguments,making it a pain for template authors to pass in all the arguments and remembertheir order. To solve this, Django provides a takes_context
option forinclusion tags. If you specify takes_context
in creating a template tag,the tag will have no required arguments, and the underlying Python functionwill have one argument — the template context as of when the tag was called.
For example, say you're writing an inclusion tag that will always be used in acontext that contains home_link
and home_title
variables that pointback to the main page. Here's what the Python function would look like:
- @register.inclusion_tag('link.html', takes_context=True)
def jump_link(context):
return {
'link': context['home_link'],
'title': context['home_title'],
}
Note that the first parameter to the function must be called context
.
In that register.inclusion_tag()
line, we specified takes_context=True
and the name of the template. Here's what the template link.html
might looklike:
- Jump directly to <a href="{{ link }}">{{ title }}</a>.
Then, any time you want to use that custom tag, load its library and call itwithout any arguments, like so:
- {% jump_link %}
Note that when you're using takes_context=True
, there's no need to passarguments to the template tag. It automatically gets access to the context.
The takes_context
parameter defaults to False
. When it's set toTrue
, the tag is passed the context object, as in this example. That's theonly difference between this case and the previous inclusion_tag
example.
inclusion_tag
functions may accept any number of positional or keywordarguments. For example:
- @register.inclusion_tag('my_template.html')
def my_tag(a, b, args, *kwargs):
warning = kwargs['warning']
profile = kwargs['profile']
…
return …
Then in the template any number of arguments, separated by spaces, may bepassed to the template tag. Like in Python, the values for keyword argumentsare set using the equal sign ("=
") and must be provided after thepositional arguments. For example:
- {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
Advanced custom template tags
Sometimes the basic features for custom template tag creation aren't enough.Don't worry, Django gives you complete access to the internals required to builda template tag from the ground up.
A quick overview
The template system works in a two-step process: compiling and rendering. Todefine a custom template tag, you specify how the compilation works and howthe rendering works.
When Django compiles a template, it splits the raw template text into''nodes''. Each node is an instance of django.template.Node
and hasa render()
method. A compiled template is, simply, a list of Node
objects. When you call render()
on a compiled template object, the templatecalls render()
on each Node
in its node list, with the given context.The results are all concatenated together to form the output of the template.
Thus, to define a custom template tag, you specify how the raw template tag isconverted into a Node
(the compilation function), and what the node'srender()
method does.
Writing the compilation function
For each template tag the template parser encounters, it calls a Pythonfunction with the tag contents and the parser object itself. This function isresponsible for returning a Node
instance based on the contents of the tag.
For example, let's write a full implementation of our simple template tag,{% current_time %}
, that displays the current date/time, formatted accordingto a parameter given in the tag, in strftime()
syntax. It's a goodidea to decide the tag syntax before anything else. In our case, let's say thetag should be used like this:
- <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
The parser for this function should grab the parameter and create a Node
object:
- from django import template
- def do_current_time(parser, token):
- try:
- # split_contents() knows not to split quoted strings.
- tag_name, format_string = token.split_contents()
- except ValueError:
- raise template.TemplateSyntaxError(
- "%r tag requires a single argument" % token.contents.split()[0]
- )
- if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
- raise template.TemplateSyntaxError(
- "%r tag's argument should be in quotes" % tag_name
- )
- return CurrentTimeNode(format_string[1:-1])
注意:
parser
is the template parser object. We don't need it in thisexample.token.contents
is a string of the raw contents of the tag. In ourexample, it's'current_time "%Y-%m-%d %I:%M %p"'
.- The
token.splitcontents()
method separates the arguments on spaceswhile keeping quoted strings together. The more straightforwardtoken.contents.split()
wouldn't be as robust, as it would naivelysplit on _all spaces, including those within quoted strings. It's a goodidea to always usetoken.split_contents()
. - This function is responsible for raising
django.template.TemplateSyntaxError
, with helpful messages, forany syntax error. - The
TemplateSyntaxError
exceptions use thetag_name
variable.Don't hard-code the tag's name in your error messages, because thatcouples the tag's name to your function.token.contents.split()[0]
will ''always'' be the name of your tag — even when the tag has noarguments. - The function returns a
CurrentTimeNode
with everything the node needsto know about this tag. In this case, it just passes the argument —"%Y-%m-%d %I:%M %p"
. The leading and trailing quotes from thetemplate tag are removed informat_string[1:-1]
. - The parsing is very low-level. The Django developers have experimentedwith writing small frameworks on top of this parsing system, usingtechniques such as EBNF grammars, but those experiments made the templateengine too slow. It's low-level because that's fastest.
Writing the renderer
The second step in writing custom tags is to define a Node
subclass thathas a render()
method.
Continuing the above example, we need to define CurrentTimeNode
:
- import datetime
- from django import template
- class CurrentTimeNode(template.Node):
- def __init__(self, format_string):
- self.format_string = format_string
- def render(self, context):
- return datetime.datetime.now().strftime(self.format_string)
注意:
init()
gets theformatstring
fromdocurrent_time()
.Always pass any options/parameters/arguments to aNode
via its__init
()
.- The
render()
method is where the work actually happens. render()
should generally fail silently, particularly in a productionenvironment. In some cases however, particularly ifcontext.template.engine.debug
isTrue
, this method may raise anexception to make debugging easier. For example, several core tags raisedjango.template.TemplateSyntaxError
if they receive the wrong number ortype of arguments.
Ultimately, this decoupling of compilation and rendering results in anefficient template system, because a template can render multiple contextswithout having to be parsed multiple times.
自动转义的注意事项
The output from template tags is not automatically run through theauto-escaping filters (with the exception ofsimple_tag()
as described above). However, thereare still a couple of things you should keep in mind when writing a templatetag.
If the render()
function of your template stores the result in a contextvariable (rather than returning the result in a string), it should take careto call mark_safe()
if appropriate. When the variable is ultimatelyrendered, it will be affected by the auto-escape setting in effect at thetime, so content that should be safe from further escaping needs to be markedas such.
Also, if your template tag creates a new context for performing somesub-rendering, set the auto-escape attribute to the current context's value.The init
method for the Context
class takes a parameter calledautoescape
that you can use for this purpose. For example:
- from django.template import Context
- def render(self, context):
- # ...
- new_context = Context({'var': obj}, autoescape=context.autoescape)
- # ... Do something with new_context ...
This is not a very common situation, but it's useful if you're rendering atemplate yourself. For example:
- def render(self, context):
- t = context.template.engine.get_template('small_fragment.html')
- return t.render(Context({'var': obj}, autoescape=context.autoescape))
If we had neglected to pass in the current context.autoescape
value to ournew Context
in this example, the results would have always beenautomatically escaped, which may not be the desired behavior if the templatetag is used inside a {% autoescape off %}
block.
Thread-safety considerations
Once a node is parsed, its render
method may be called any number of times.Since Django is sometimes run in multi-threaded environments, a single node maybe simultaneously rendering with different contexts in response to two separaterequests. Therefore, it's important to make sure your template tags are threadsafe.
To make sure your template tags are thread safe, you should never store stateinformation on the node itself. For example, Django provides a builtincycle
template tag that cycles among a list of given strings each timeit's rendered:
- {% for o in some_list %}
- <tr class="{% cycle 'row1' 'row2' %}">
- ...
- </tr>
- {% endfor %}
A naive implementation of CycleNode
might look something like this:
- import itertools
- from django import template
- class CycleNode(template.Node):
- def __init__(self, cyclevars):
- self.cycle_iter = itertools.cycle(cyclevars)
- def render(self, context):
- return next(self.cycle_iter)
But, suppose we have two templates rendering the template snippet from above atthe same time:
- Thread 1 performs its first loop iteration,
CycleNode.render()
returns 'row1' - Thread 2 performs its first loop iteration,
CycleNode.render()
returns 'row2' - Thread 1 performs its second loop iteration,
CycleNode.render()
returns 'row1' - Thread 2 performs its second loop iteration,
CycleNode.render()
returns 'row2'
The CycleNode is iterating, but it's iterating globally. As far as Thread 1and Thread 2 are concerned, it's always returning the same value. This isobviously not what we want!
To address this problem, Django provides a render_context
that's associatedwith the context
of the template that is currently being rendered. Therender_context
behaves like a Python dictionary, and should be used tostore Node
state between invocations of the render
method.
Let's refactor our CycleNode
implementation to use the render_context
:
- class CycleNode(template.Node):
- def __init__(self, cyclevars):
- self.cyclevars = cyclevars
- def render(self, context):
- if self not in context.render_context:
- context.render_context[self] = itertools.cycle(self.cyclevars)
- cycle_iter = context.render_context[self]
- return next(cycle_iter)
Note that it's perfectly safe to store global information that will not changethroughout the life of the Node
as an attribute. In the case ofCycleNode
, the cyclevars
argument doesn't change after the Node
isinstantiated, so we don't need to put it in the render_context
. But stateinformation that is specific to the template that is currently being rendered,like the current iteration of the CycleNode
, should be stored in therender_context
.
注解
Notice how we used self
to scope the CycleNode
specific informationwithin the render_context
. There may be multiple CycleNodes
in agiven template, so we need to be careful not to clobber another node'sstate information. The easiest way to do this is to always use self
asthe key into render_context
. If you're keeping track of several statevariables, make render_context[self]
a dictionary.
Registering the tag
Finally, register the tag with your module's Library
instance, as explainedin writing custom template filtersabove. Example:
- register.tag('current_time', do_current_time)
The tag()
method takes two arguments:
- The name of the template tag — a string. If this is left out, thename of the compilation function will be used.
- The compilation function — a Python function (not the name of thefunction as a string).
As with filter registration, it is also possible to use this as a decorator:
If you leave off the name
argument, as in the second example above, Djangowill use the function's name as the tag name.
Passing template variables to the tag
Although you can pass any number of arguments to a template tag usingtoken.split_contents()
, the arguments are all unpacked asstring literals. A little more work is required in order to pass dynamiccontent (a template variable) to a template tag as an argument.
While the previous examples have formatted the current time into a string andreturned the string, suppose you wanted to pass in aDateTimeField
from an object and have the templatetag format that date-time:
- <p>This post was last updated at {% format_time blog_entry.date_updated "%Y-%m-%d %I:%M %p" %}.</p>
Initially, token.split_contents()
will return three values:
- The tag name
format_time
. - The string
'blog_entry.date_updated'
(without the surroundingquotes). - The formatting string
'"%Y-%m-%d %I:%M %p"'
. The return value fromsplit_contents()
will include the leading and trailing quotes forstring literals like this.
Now your tag should begin to look like this:
- from django import template
- def do_format_time(parser, token):
- try:
- # split_contents() knows not to split quoted strings.
- tag_name, date_to_be_formatted, format_string = token.split_contents()
- except ValueError:
- raise template.TemplateSyntaxError(
- "%r tag requires exactly two arguments" % token.contents.split()[0]
- )
- if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
- raise template.TemplateSyntaxError(
- "%r tag's argument should be in quotes" % tag_name
- )
- return FormatTimeNode(date_to_be_formatted, format_string[1:-1])
You also have to change the renderer to retrieve the actual contents of thedate_updated
property of the blog_entry
object. This can beaccomplished by using the Variable()
class in django.template
.
To use the Variable
class, simply instantiate it with the name of thevariable to be resolved, and then call variable.resolve(context)
. So,for example:
- class FormatTimeNode(template.Node):
- def __init__(self, date_to_be_formatted, format_string):
- self.date_to_be_formatted = template.Variable(date_to_be_formatted)
- self.format_string = format_string
- def render(self, context):
- try:
- actual_date = self.date_to_be_formatted.resolve(context)
- return actual_date.strftime(self.format_string)
- except template.VariableDoesNotExist:
- return ''
Variable resolution will throw a VariableDoesNotExist
exception if itcannot resolve the string passed to it in the current context of the page.
Setting a variable in the context
The above examples simply output a value. Generally, it's more flexible if yourtemplate tags set template variables instead of outputting values. That way,template authors can reuse the values that your template tags create.
To set a variable in the context, just use dictionary assignment on the contextobject in the render()
method. Here's an updated version ofCurrentTimeNode
that sets a template variable current_time
instead ofoutputting it:
- import datetime
- from django import template
- class CurrentTimeNode2(template.Node):
- def __init__(self, format_string):
- self.format_string = format_string
- def render(self, context):
- context['current_time'] = datetime.datetime.now().strftime(self.format_string)
- return ''
Note that render()
returns the empty string. render()
should alwaysreturn string output. If all the template tag does is set a variable,render()
should return the empty string.
Here's how you'd use this new version of the tag:
- {% current_time "%Y-%M-%d %I:%M %p" %}<p>The time is {{ current_time }}.</p>
Variable scope in context
Any variable set in the context will only be available in the sameblock
of the template in which it was assigned. This behavior isintentional; it provides a scope for variables so that they don't conflictwith context in other blocks.
But, there's a problem with CurrentTimeNode2
: The variable namecurrent_time
is hard-coded. This means you'll need to make sure yourtemplate doesn't use {{ current_time }}
anywhere else, because the{% current_time %}
will blindly overwrite that variable's value. A cleanersolution is to make the template tag specify the name of the output variable,like so:
- {% current_time "%Y-%M-%d %I:%M %p" as my_current_time %}
- <p>The current time is {{ my_current_time }}.</p>
To do that, you'll need to refactor both the compilation function and Node
class, like so:
- import re
- class CurrentTimeNode3(template.Node):
- def __init__(self, format_string, var_name):
- self.format_string = format_string
- self.var_name = var_name
- def render(self, context):
- context[self.var_name] = datetime.datetime.now().strftime(self.format_string)
- return ''
- def do_current_time(parser, token):
- # This version uses a regular expression to parse tag contents.
- try:
- # Splitting by None == splitting by spaces.
- tag_name, arg = token.contents.split(None, 1)
- except ValueError:
- raise template.TemplateSyntaxError(
- "%r tag requires arguments" % token.contents.split()[0]
- )
- m = re.search(r'(.*?) as (\w+)', arg)
- if not m:
- raise template.TemplateSyntaxError("%r tag had invalid arguments" % tag_name)
- format_string, var_name = m.groups()
- if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
- raise template.TemplateSyntaxError(
- "%r tag's argument should be in quotes" % tag_name
- )
- return CurrentTimeNode3(format_string[1:-1], var_name)
The difference here is that do_current_time()
grabs the format string andthe variable name, passing both to CurrentTimeNode3
.
Finally, if you only need to have a simple syntax for your customcontext-updating template tag, consider using thesimple_tag()
shortcut, which supports assigningthe tag results to a template variable.
Parsing until another block tag
Template tags can work in tandem. For instance, the standard{% comment %}
tag hides everything until {% endcomment %}
.To create a template tag such as this, use parser.parse()
in yourcompilation function.
Here's how a simplified {% comment %}
tag might be implemented:
- def do_comment(parser, token):
- nodelist = parser.parse(('endcomment',))
- parser.delete_first_token()
- return CommentNode()
- class CommentNode(template.Node):
- def render(self, context):
- return ''
注解
The actual implementation of {% comment %}
is slightlydifferent in that it allows broken template tags to appear between{% comment %}
and {% endcomment %}
. It does so by callingparser.skip_past('endcomment')
instead of parser.parse(('endcomment',))
followed by parser.delete_first_token()
, thus avoiding the generation of anode list.
parser.parse()
takes a tuple of names of block tags ''to parse until''. Itreturns an instance of django.template.NodeList
, which is a list ofall Node
objects that the parser encountered ''before'' it encounteredany of the tags named in the tuple.
In "nodelist = parser.parse(('endcomment',))"
in the above example,nodelist
is a list of all nodes between the {% comment %}
and{% endcomment %}
, not counting {% comment %}
and {% endcomment %}
themselves.
After parser.parse()
is called, the parser hasn't yet "consumed" the{% endcomment %}
tag, so the code needs to explicitly callparser.delete_first_token()
.
CommentNode.render()
simply returns an empty string. Anything between{% comment %}
and {% endcomment %}
is ignored.
Parsing until another block tag, and saving contents
In the previous example, do_comment()
discarded everything between{% comment %}
and {% endcomment %}
. Instead of doing that, it'spossible to do something with the code between block tags.
For example, here's a custom template tag, {% upper %}
, that capitalizeseverything between itself and {% endupper %}
.
Usage:
- {% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %}
As in the previous example, we'll use parser.parse()
. But this time, wepass the resulting nodelist
to the Node
:
- def do_upper(parser, token):
- nodelist = parser.parse(('endupper',))
- parser.delete_first_token()
- return UpperNode(nodelist)
- class UpperNode(template.Node):
- def __init__(self, nodelist):
- self.nodelist = nodelist
- def render(self, context):
- output = self.nodelist.render(context)
- return output.upper()
The only new concept here is the self.nodelist.render(context)
inUpperNode.render()
.
For more examples of complex rendering, see the source code of{% for %}
in django/template/defaulttags.py
and{% if %}
in django/template/smartif.py
.