Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An adaptor to use Mustache as a templating engine in Django 1.8+
import io
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import TemplateDoesNotExist
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from django.utils.html import conditional_escape
from pystache import parse, Renderer
class DjangoMustacheRenderer(Renderer):
def str_coerce(self, val):
if not val:
val = ''
return conditional_escape(val)
class MustacheEngine(BaseEngine):
# Name of the subdirectory containing the templates for this engine
# inside an installed application.
app_dirname = 'mustache'
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(MustacheEngine, self).__init__(params)
self.renderer = DjangoMustacheRenderer(**options)
def from_string(self, template_code):
return Template(renderer=self.renderer, template=template_code)
def get_template(self, template_name):
for template_file in self.iter_template_filenames(template_name):
with, encoding=settings.FILE_CHARSET) as fp:
template_code =
except IOError:
return Template(renderer=self.renderer, template=template_code)
raise TemplateDoesNotExist(template_name)
class Template(object):
def __init__(self, renderer, template):
self.renderer = renderer
self.template_parsed = parse(template)
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
return self.renderer.render(self.template_parsed, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.