2

I am using Django to build up my web project. As known that mako and Jinja2 template are faster that the one Django's given, I start finding way to integrate mako and Jinja2 into Django with using the Django's way of render_to_response method. After a lot research, I finally figure out the way to make this happen. However, in my integration, the jmeter's performance is something like Jinja2 (3ms) > Django's template (50ms) > mako (218ms).

If I went wrong with something?....Or pls help to advise some best practice to integrate jinja2 and mako.

Below is the coding ()

Mako2django.py

from django.http import HttpResponse
from django.template import Context
from mako.lookup import TemplateLookup
from mysite.settings import TEMPLATE_DIRS 

   def render_to_mako(t,c=None,context_instance=None):
   path = TEMPLATE_DIRS
   makolookup = TemplateLookup(directories=[path],output_encoding='utf-   8',input_encoding='utf-8')
mako_temp = makolookup.get_template(t)
if context_instance:
    context_instance.update(c)
else:
    context_instance = Context(c)
data = {}
for d in context_instance:data.update(d)
return HttpResponse(mako_temp.render(**data))

Jinja2django.py

from django.http import HttpResponse
from django.conf import settings
from jinja2 import Environment, ChoiceLoader, FileSystemLoader

# Setup environment
default_mimetype = getattr(settings, 'DEFAULT_CONTENT_TYPE')

# Create the Jinja2 Environment
   env = Environment(
   line_statement_prefix='%',
   line_comment_prefix='##',
   loader=ChoiceLoader([FileSystemLoader(path) for path in getattr(settings,       'TEMPLATE_DIRS', ())]))

def render_to_string(filename, context={}):
   return env.get_template(filename).render(**context)

def render_to_jinja2(filename, context={},mimetype=default_mimetype, request = None):
   if request: context['request'] = request
   return HttpResponse(render_to_string(filename, context),mimetype=mimetype)

The view.py is similar as below

from draft.jinja2django import render_to_jinja2

def view1(request):
    b = "helloworld"
    return render_to_jinja2('testjinja.html', context={"test":b})
chow
  • 33
  • 5

1 Answers1

2

Starting from Django 1.2 you can create your custom template loader that returns your Template object. Doing that you can make django's render_to_response, render_to_string and counterparts render using your template system.

I am using this one: https://gist.github.com/972162

It loads Jinja2 templates transparently and falls back to Django templates for admin, contrib and third-party apps.

Suor
  • 2,845
  • 1
  • 22
  • 28