Jinja policies in Django projects
Jinja policies are used to set the global behavior of Jinja built-in filters and other template constructs. Jinja policies are set in Jinja environments -- just like Jinja globals in listing 4-11 or custom Jinja filters & tests in listing 4-25.
For example, you can use Jinja
policies to alter the way the json
or
urlize
built-in filters operate by default. Listing
4-30 illustrates a custom Jinja environment that alters the Jinja
built-in truncate
filter and sets the
leeway
option to 0
.
Listing 4-30 Custom Jinja environment with policies
from jinja2.environment import Environment from coffeehouse.jinja.filters import customcoffee, squarerootintext, startswithvowel class JinjaEnvironment(Environment): def __init__(self,**kwargs): super(JinjaEnvironment, self).__init__(**kwargs) self.policies['truncate.leeway'] = 0
As you can see in listing 4-30,
to register Jinja policies you access self.policies
and assign it the policy key name[8] -- in this
case corresponding to truncate.leeway
-- along with
the policy value -- in this case corresponding to 0
.
By setting the Jinja policy in listing 4-30, anytime you use the
truncate
filter in Jinja templates, the
leeway
is set to 0
, instead of the
default 5
.