Il linguaggio di template di Django arriva come un’ampia varietà di filtri e tag built-in progettati per far fronte alle necessità di logica di presentazione delle tue applicazioni. Eppure, potresti trovarti nella condizione di aver bisogno di funzionalità che non sono coperte dal set di primitive di template del core. Puoi estendere il motore di template definendo dei tag e filtri personalizzati usando Python e poi renderli disponibili ai tuoi template utilizzando il tag {% load %}
Il posto più comune in cui specificare tag e filtri di template personalizzati è nell’applicazione Django. Se sono collegati ad una app esistente, ha senso metterli lì; altrimento, possono essere aggiunti ad una nuova app. Quando una applicazione Django viene aggiunta ad INSTALLED_APPS, ogni tag che definisce nella locazione convenzionale descritta qui sotto viene automaticamente reso disponibile al caricamento nei template.
L’applicazione deve contenere una directory templatetags, allo stesso livello di models.py, views.py, ecc. Se non esiste già, creala - non dimenticare il file __init__.py per assicurarti che la directory sia trattata come un package Python.
I server di sviluppo non si riavviano in automatico
Dopo aver aggiunto il modulo templatetags, avrai bisogno di riavviare il tuo server prima di poter utilizzare i tag o i filtri nei template.
I tuoi tag e filtri personalizzati vivranno in un modulo nella directory templatetags. Il nome del file del modulo è il nome che userai per caricare successivamente i tag, quindi fai attenzione a sceglierne uno che non vada in conflitto con i tag ed i filtri personalizzati di un’altra applicazione.
Per esempio, se i tags/filtri personalizzati sono in un file chiamato poll_extras.py, il layout della tua applicazione potrebbe assomigliare a questo:
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
E nel tuo template utilizzerai i seguenti:
{% load poll_extras %}
Le app che contengono i tag personalizzati devono trovarsi in INSTALLED_APPS affinchè il tag {% load %} funzioni. E” una feature di sicurezza: ti rende possibile fare hosting di codice Python per molte librerie di template su una singola macchina host senza abilitare l’accesso a tutte per ogni installazione di Django.
Non c’è limite al numero di moduli che puoi aggiungere nel package templatetags. Tieni solo presente che uno statement {% load %} caricherà tag/filtri per un dato nome di modulo Python, non per il nome dell’app.
Per essere una libreria di tag valida, il modulo deve contenere una variabile module-level chiamata register, che è una instanza di template.Library, nella quale sono registrati tutti i tag ed i filtri. Così, nella parte più alta del tuo modulo, metti quanto segue:
from django import template
register = template.Library()
Alternativamente, i moduli per i tag di template possono essere registrati attraverso l’argomento 'libraries' in DjangoTemplates. Risulta utile quando vuoi usare una label differente rispetto al nome del modulo di tag di template quando carichi i tag di template. Ti permette anche di registrare tag senza installare una applicazione.
Dietro le quinte
Per molti più esempi, leggi il codice sorgente dei filtri di default e dei tag di Django. Si trovano rispettivamente in django/template/defaultfilters.py e django/template/defaulttags.py.
Per avere più informazioni sul tag load, leggi la sua documentazione.
I filtri custom sono funzioni Python che prendono uno o due argomenti.
Per esempio, nel filtro «{{ var|foo:»bar» }}», al filtro foo sarà passata la variabile «var» e l’argomento «bar».
Dal momento che il linguaggio di template non fornisce la gestione delle eccezioni, ogni eccezione sollevata dal un filtro di template sarà esposta come errore del server. Quindi, le funzioni di filtro dovrebbero evitare di sollevare eccezioni se c’è un valore di fallback ragionevole da restituire. In caso di input che rappresenti un chiaro bug in un template, sollevare una eccezione può ancora essere meglio di un fallimento silente che nasconde il bug.
Un esempio della definizione di un filtro
def cut(value, arg):
"""Removes all values of arg from the given string"""
return value.replace(arg, '')
E qui un esempio di come il viene usato
{{ somevariable|cut:"0" }}
Moltri filtri non prendono argomenti. In questo caso, lascia l’argomento fuori dalla tua funzione:
def lower(value): # Only one argument.
"""Converts a string into all lowercase"""
return value.lower()
django.template.Library.filter()¶Dopo aver scritto la definizione del filtro, bisogna registrarlo con l’istanza di «Library» al fine di renderlo disponibile per l’uso nel linguaggio dei template di Django.
register.filter('cut', cut)
register.filter('lower', lower)
Il metodo «Library.filter()» prende due argomenti:
In alternativa puoi usare register.filter() come decorator
@register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
@register.filter
def lower(value):
return value.lower()
Se lasci fuori l’argomento name, come nell’esempio sopra, Django userà il nome della funzione come nome di filtro.
Infine, register.filter() accetta anche tre argomenti keyword, is_safe, needs_autoescape e expects_localtime. Questi argomenti sono descritti in filtri ed auto-escaping e filtri e time zones qui sotto.
django.template.defaultfilters.stringfilter()¶Se stai scrivendo un filtro di template che si aspetta solo una stringa come primo argomento, dovresti utilizzare il decoratore stringfilter. Questo convertirà un oggetto al suo valore stringa prima di passarlo alla tua funzione:
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def lower(value):
return value.lower()
In questo modo, sarà in grado di passare, diciamo, un intero a questo filtro e non causerà un AttributeError (perchè gli integer non hanno metodi lower())
Scrivendo un filtro personalizzato, pensa a come il filtro interagirà con i comportamenti di auto-escaping di Django. Nota che nel codice di template possono essere passati due tipi di stringhe:
Le Raw strings sono le stringhe native di Python. All’output, sono oggetto di escape se è attivo l’auto-escape o altrimenti presentate senza cambiamenti.
Le Safe strings sono stringhe che sono state marcate come safe da ulteriori escape a tempo di output. Ogni escaping necessario è già stato fatto. Sono usate comunemente per output che contiene HTML grezzo che deve essere interpretato così come è client-side.
Internamente, queste stringhe sono di tipo SafeString. Puoi testarle utilizzando del codice come questo:
from django.utils.safestring import SafeString
if isinstance(value, SafeString):
# Do something with the "safe" string.
...
Il codice dei filtri di template ricade in una delle due situazioni:
Your filter does not introduce any HTML-unsafe characters (<, >,
', " or &) into the result that were not already present. In
this case, you can let Django take care of all the auto-escaping
handling for you. All you need to do is set the is_safe flag to True
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 your filter, the result will still be «safe» and if a non-safe string is passed in, Django will automatically escape it, if necessary.
You can think of this as meaning «this filter is safe – it doesn’t introduce any possibility of unsafe HTML.»
The reason is_safe is necessary is because there are plenty of
normal string operations that will turn a SafeData object back into
a normal str object and, rather than try to catch them all, which would
be very difficult, Django repairs the damage after the filter has completed.
For example, suppose you have a filter that adds the string xx to
the end of any input. Since this introduces no dangerous HTML characters
to the result (aside from any that were already present), you should
mark 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 marked as «safe».
By default, is_safe is False, and you can omit it from any filters
where it isn’t required.
Be careful when deciding if your filter really does leave safe strings
as safe. If you’re removing characters, you might inadvertently leave
unbalanced HTML tags or entities in the result. For example, removing a
> from the input might turn <a> into <a, which would need to
be escaped on output to avoid causing problems. Similarly, removing a
semicolon (;) can turn & into &, which is no longer a
valid entity and thus needs further escaping. Most cases won’t be nearly
this tricky, but keep an eye out for any problems like that when
reviewing your code.
Marking a filter is_safe will coerce the filter’s return value to
a string. If your filter should return a boolean or other non-string
value, marking it is_safe will probably have unintended
consequences (such as converting a boolean False to the string
“False”).
Alternatively, your filter code can manually take care of any necessary escaping. This is necessary when you’re introducing new HTML markup into the result. You want to mark the output as safe from further escaping so that your HTML markup isn’t escaped further, so you’ll need to handle the input yourself.
To mark the output as a safe string, use
django.utils.safestring.mark_safe().
Be careful, though. You need to do more than just mark the output as safe. You need to ensure it really is safe, and what you do depends on whether auto-escaping is in effect. The idea is to write filters that can operate in templates where auto-escaping is either on or off in order to make things easier for your template authors.
In order for your filter to know the current auto-escaping state, set the
needs_autoescape flag to True when you register your filter function.
(If you don’t specify this flag, it defaults to False). This flag tells
Django that your filter function wants to be passed an extra keyword
argument, called autoescape, that is True if auto-escaping is in
effect and False otherwise. It is recommended to set the default of the
autoescape parameter to True, so that if you call the function
from Python code it will have escaping enabled by default.
Ad esempio, scriviamo un filtro che enfatizza il primo carattere di una stringa:
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 mean
that our function will know whether automatic escaping is in effect when the
filter is called. We use autoescape to decide whether the input data
needs to be passed through django.utils.html.conditional_escape or not.
(In the latter case, we use the identity function as the «escape» function.)
The conditional_escape() function is like escape() except it only
escapes input that is not a SafeData instance. If a SafeData
instance is passed to conditional_escape(), the data is returned
unchanged.
Finally, in the above example, we remember to mark the result as safe so that our HTML is inserted directly into the template without further escaping.
There’s no need to worry about the is_safe flag in this case
(although including it wouldn’t hurt anything). Whenever you manually
handle the auto-escaping issues and return a safe string, the
is_safe flag won’t change anything either way.
Avvertimento
Evitare le vulnerabilità XSS quando si riutilizzano i filtri built-in
I filtri built-in di Django hanno di default «autoescape=True» al fine di assicurare il corretto autoescaping ed evitare vulnerabilità di tipo cross-site script.
In older versions of Django, be careful when reusing Django’s built-in
filters as autoescape defaults to None. You’ll need to pass
autoescape=True to get autoescaping.
For example, if you wanted to write a custom filter called
urlize_and_linebreaks that combined the urlize and
linebreaksbr 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
)
Poi
{{ 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 to
True:
@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 zone aware datetime, Django will convert it to the current time zone before passing it to your filter when appropriate, according to rules for time zones conversions in templates.
Tags are more complex than filters, because tags can do anything. Django provides 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 from scratch for those cases when the shortcuts aren’t powerful enough.
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 on
the input arguments and some external information. For example, a
current_time tag might accept a format string and return the time as a
string formatted accordingly.
To ease the creation of these types of tags, Django provides a helper function,
simple_tag. This function, which is a method of
django.template.Library, takes a function that accepts any number of
arguments, wraps it in a render function and the other necessary bits
mentioned 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:
Unlike other tag utilities, simple_tag passes its output through
conditional_escape() if the template context is in
autoescape mode, to ensure correct HTML and protect you from XSS
vulnerabilities.
If additional escaping is not desired, you will need to use
mark_safe() if you are absolutely sure that your
code does not contain XSS vulnerabilities. For building small HTML snippets,
use of format_html() instead of mark_safe() is
strongly recommended.
If your template tag needs to access the current context, you can use the
takes_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)
Nota che il primo argomento deve chiamarsi «context»
For more information on how the takes_context option works, see the section
on inclusion tags.
Se hai bisogno dirinominare il tag, puoi fornirne un nome personalizzato:
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 keyword
arguments. 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 be
passed to the template tag. Like in Python, the values for keyword arguments
are set using the equal sign (»=») and must be provided after the
positional 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 than
directly outputting it. This is done by using the as argument followed by
the variable name. Doing so enables you to output the content yourself where
you see fit:
{% current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>
django.template.Library.inclusion_tag()¶Another common type of template tag is the type that displays some data by
rendering another template. For example, Django’s admin interface uses custom
template tags to display the buttons along the bottom of the «add/change» form
pages. Those buttons always look the same, but the link targets change
depending on the object being edited – so they’re a perfect case for using a
small template that is filled with details from the current object. (In the
admin’s case, this is the submit_row tag.)
I tag di questo tipo sono detti «tag di inclusione»
Writing inclusion tags is probably best demonstrated by example. Let’s write a
tag that outputs a list of choices for a given Poll object, such as was
created in the tutorials. We’ll use the tag like this:
{% show_results poll %}
… e l’output sarà qualcosa di simile a questo:
<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 of data for the result. The important point here is we only need to return a dictionary, not anything more complex. This will be used as a template context for 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 a fixed feature of the tag: the tag writer specifies it, not the template designer. Following our example, the template is very short:
<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 is
in a file called results.html in a directory that’s searched by the
template 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 a
django.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 remember
their order. To solve this, Django provides a takes_context option for
inclusion tags. If you specify takes_context in creating a template tag,
the tag will have no required arguments, and the underlying Python function
will 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 a
context that contains home_link and home_title variables that point
back 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 look
like:
Jump directly to <a href="{{ link }}">{{ title }}</a>.
Then, any time you want to use that custom tag, load its library and call it without any arguments, like so:
{% jump_link %}
Note that when you’re using takes_context=True, there’s no need to pass
arguments to the template tag. It automatically gets access to the context.
The takes_context parameter defaults to False. When it’s set to
True, the tag is passed the context object, as in this example. That’s the
only difference between this case and the previous inclusion_tag example.
inclusion_tag functions may accept any number of positional or keyword
arguments. 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 be
passed to the template tag. Like in Python, the values for keyword arguments
are set using the equal sign (»=») and must be provided after the
positional arguments. For example:
{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
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 build a template tag from the ground up.
The template system works in a two-step process: compiling and rendering. To define a custom template tag, you specify how the compilation works and how the 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 has
a render() method. A compiled template is a list of Node objects. When
you call render() on a compiled template object, the template calls
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 is
converted into a Node (the compilation function), and what the node’s
render() method does.
For each template tag the template parser encounters, it calls a Python
function with the tag contents and the parser object itself. This function is
responsible for returning a Node instance based on the contents of the tag.
For example, let’s write a full implementation of our template tag,
{% current_time %}, that displays the current date/time, formatted according
to a parameter given in the tag, in strftime() syntax. It’s a good
idea to decide the tag syntax before anything else. In our case, let’s say the
tag 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])
Note:
parser è l’oggetto parser di template. Non ne abbiamo bisogno in questo esempio.token.contents is a string of the raw contents of the tag. In our
example, it’s 'current_time "%Y-%m-%d %I:%M %p"'.token.split_contents() method separates the arguments on spaces
while keeping quoted strings together. The more straightforward
token.contents.split() wouldn’t be as robust, as it would naively
split on all spaces, including those within quoted strings. It’s a good
idea to always use token.split_contents().django.template.TemplateSyntaxError, with helpful messages, for
any syntax error.TemplateSyntaxError exceptions use the tag_name variable.
Don’t hard-code the tag’s name in your error messages, because that
couples the tag’s name to your function. token.contents.split()[0]
will “”always”” be the name of your tag – even when the tag has no
arguments.CurrentTimeNode with everything the node needs
to know about this tag. In this case, it passes the argument –
"%Y-%m-%d %I:%M %p". The leading and trailing quotes from the
template tag are removed in format_string[1:-1].The second step in writing custom tags is to define a Node subclass that
has 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)
Note:
__init__() gets the format_string from do_current_time().
Always pass any options/parameters/arguments to a Node via its
__init__().render() method is where the work actually happens.render() should generally fail silently, particularly in a production
environment. In some cases however, particularly if
context.template.engine.debug is True, this method may raise an
exception to make debugging easier. For example, several core tags raise
django.template.TemplateSyntaxError if they receive the wrong number or
type of arguments.Ultimately, this decoupling of compilation and rendering results in an efficient template system, because a template can render multiple contexts without having to be parsed multiple times.
The output from template tags is not automatically run through the
auto-escaping filters (with the exception of
simple_tag() as described above). However, there
are still a couple of things you should keep in mind when writing a template
tag.
If the render() method of your template tag stores the result in a context
variable (rather than returning the result in a string), it should take care
to call mark_safe() if appropriate. When the variable is ultimately
rendered, it will be affected by the auto-escape setting in effect at the
time, so content that should be safe from further escaping needs to be marked
as such.
Also, if your template tag creates a new context for performing some
sub-rendering, set the auto-escape attribute to the current context’s value.
The __init__ method for the Context class takes a parameter called
autoescape 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 ...
Non è una situazione molto comune, ma è utile se si fa rendering di un template da soli. Per esempio:
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 our
new Context in this example, the results would have always been
automatically escaped, which may not be the desired behavior if the template
tag is used inside a {% autoescape off %} block.
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 may
be simultaneously rendering with different contexts in response to two separate
requests. Therefore, it’s important to make sure your template tags are thread
safe.
To make sure your template tags are thread safe, you should never store state
information on the node itself. For example, Django provides a builtin
cycle template tag that cycles among a list of given strings each time
it’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 at the same time:
CycleNode.render()
returns “row1”CycleNode.render()
returns “row2”CycleNode.render()
returns “row1”CycleNode.render()
returns “row2”The CycleNode is iterating, but it’s iterating globally. As far as Thread 1 and Thread 2 are concerned, it’s always returning the same value. This is not what we want!
To address this problem, Django provides a render_context that’s associated
with the context of the template that is currently being rendered. The
render_context behaves like a Python dictionary, and should be used to
store 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 change
throughout the life of the Node as an attribute. In the case of
CycleNode, the cyclevars argument doesn’t change after the Node is
instantiated, so we don’t need to put it in the render_context. But state
information that is specific to the template that is currently being rendered,
like the current iteration of the CycleNode, should be stored in the
render_context.
Nota
Notice how we used self to scope the CycleNode specific information
within the render_context. There may be multiple CycleNodes in a
given template, so we need to be careful not to clobber another node’s
state information. The easiest way to do this is to always use self as
the key into render_context. If you’re keeping track of several state
variables, make render_context[self] a dictionary.
Finally, register the tag with your module’s Library instance, as explained
in writing custom template tags
above. Example:
register.tag('current_time', do_current_time)
Il methodo tag() ha bisogni di due argomenti:
As with filter registration, it is also possible to use this as a decorator:
@register.tag(name="current_time")
def do_current_time(parser, token):
...
@register.tag
def shout(parser, token):
...
If you leave off the name argument, as in the second example above, Django
will use the function’s name as the tag name.
Although you can pass any number of arguments to a template tag using
token.split_contents(), the arguments are all unpacked as
string literals. A little more work is required in order to pass dynamic
content (a template variable) to a template tag as an argument.
While the previous examples have formatted the current time into a string and
returned the string, suppose you wanted to pass in a
DateTimeField from an object and have the template
tag 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:
format_time.'blog_entry.date_updated' (without the surrounding
quotes).'"%Y-%m-%d %I:%M %p"'. The return value from
split_contents() will include the leading and trailing quotes for
string 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 the
date_updated property of the blog_entry object. This can be
accomplished by using the Variable() class in django.template.
To use the Variable class, instantiate it with the name of the variable 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 it
cannot resolve the string passed to it in the current context of the page.
The above examples output a value. Generally, it’s more flexible if your template 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, use dictionary assignment on the context
object in the render() method. Here’s an updated version of
CurrentTimeNode that sets a template variable current_time instead of
outputting 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 always
return 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 same
block of the template in which it was assigned. This behavior is
intentional; it provides a scope for variables so that they don’t conflict
with context in other blocks.
But, there’s a problem with CurrentTimeNode2: The variable name
current_time is hard-coded. This means you’ll need to make sure your
template doesn’t use {{ current_time }} anywhere else, because the
{% current_time %} will blindly overwrite that variable’s value. A cleaner
solution 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 and
the variable name, passing both to CurrentTimeNode3.
Finally, if you only need to have a simple syntax for your custom
context-updating template tag, consider using the
simple_tag() shortcut, which supports assigning
the tag results to a template variable.
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 your
compilation 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 ''
Nota
The actual implementation of {% comment %} is slightly
different in that it allows broken template tags to appear between
{% comment %} and {% endcomment %}. It does so by calling
parser.skip_past('endcomment') instead of parser.parse(('endcomment',))
followed by parser.delete_first_token(), thus avoiding the generation of a
node list.
parser.parse() takes a tuple of names of block tags “”to parse until””. It
returns an instance of django.template.NodeList, which is a list of
all Node objects that the parser encountered “”before”” it encountered
any 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 call
parser.delete_first_token().
CommentNode.render() returns an empty string. Anything between
{% comment %} and {% endcomment %} is ignored.
In the previous example, do_comment() discarded everything between
{% comment %} and {% endcomment %}. Instead of doing that, it’s
possible to do something with the code between block tags.
For example, here’s a custom template tag, {% upper %}, that capitalizes
everything between itself and {% endupper %}.
Utilizzo:
{% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %}
As in the previous example, we’ll use parser.parse(). But this time, we
pass 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) in
UpperNode.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.
ago 03, 2022