Django template wrapper for Jinja2
So you decided to use Jinja2? But wait, now you want to use django template tags? Well good thing for you, so did I. It’s super easy once you know how to do it. And the cool thing is that it will automatically pick up any tempate tags registered in your install_apps.
Simply embed your extensions within the {% django %} tag extension in jinja, pass in a dictionary (at least a blank one {}) and use your django template tags as normal with one exception: more spaces
"{{" = "{ {"
"{%" = "{ %"
"}}" = "} }"
"%}" = "% }"
Example usage:
<b>hi {{name}}</b>
{% django {"name":"Bob Bobby"} %}
{# filter is a built in django template tag#}
{ % filter force_escape|lower % }
This text will be <HTML>-escaped,and will appear in all lowercase.
django name={ {name} }
jinja name={{name}}
{ % endfilter % }
{% enddjango %}
output:
<b>hi Timothy John Watts</b>
this text will be <html>-escaped,and will appear in all lowercase.
django name=bob bobby
jinja name=timothy john watts
code:
from jinja2 import Environment,PackageLoader
from jinja2 import nodes
from jinja2.ext import Extension
class DjangoTagExtension(Extension):
tags = ['django']
def __init__(self, environment):
super(DjangoTagExtension, self).__init__(environment)
def parse(self, parser):
lineno = parser.stream.next().lineno
# get an dict for the django context {}
args = [parser.parse_expression()]
body = parser.parse_statements(['name:enddjango'], drop_needle=True)
return nodes.CallBlock(self.call_method('_tag_support', args),[], [], body).set_lineno(lineno)
def _tag_support(self, context, *args,**kwargs):
"""Helper callback."""
from django.template import Context, Template
raw_template = kwargs['caller']()
raw_template = raw_template.replace("{ %","{%")
raw_template = raw_template.replace("% }","%}")
raw_template = raw_template.replace("{ {","{{")
raw_template = raw_template.replace("} }","}}")
django_template = Template(raw_template)
c = Context(context)
return django_template.render(c)
and add it to your Jinja Extensions
JINJA_EXTS = (
'path.to.DjangoTagExtension',
)