Update: I’ve posted the code at github here.
Wanting to keep my server-side and client-side templates identical, I noticed there wasn’t a good solution for using Mustache/Pystache/Handlebars templates alongside the Django templating language.
The existing one that I saw used Pystache internals, and I’m not even sure they’re still valid in the latest Pystache versions.
The other existing one that I saw let you do the equivalent of #include “something.mustache” within the Django templates, which wasn’t what I was looking for either.
So I went ahead and wrote a set of PystacheTemplate and Pystache*Loader classes which do it all within the specifications of the Django infrastructure, and, I set them up so that you can specify the exact file extensions you want them to operate on, i.e. just .mustache, .handlebars, and .hbs files by default. This doesn’t mean you can mix Mustache directly into Django templates, which doesn’t make sense (and is mildly redundant), but it does mean you can render complete Mustache template files directly, which is awesome if you’re wanting to share those templates or partials between client and server.
Copy this file somewhere into your project or app folders:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
"""
Copyright (c) 2012 Max Vilimpoc
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""
from django.template.loaders import app_directories, filesystem
from django.template.base import TemplateDoesNotExist
import pystache
import os
"""
Based on:
https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.Template
https://docs.djangoproject.com/en/dev/ref/templates/api/#loading-templates
https://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language
"""
class PystacheTemplate():
def __init__(self, templateString):
self.parsed = pystache.parse(templateString)
self.renderer = pystache.Renderer()
def render(self, context):
# Flatten the Django Context into a single dictionary.
flatContext = {}
for d in context.dicts:
flatContext.update(d)
return self.renderer.render(self.parsed, flatContext)
"""
Based on:
https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
Yeah, it's two identical classes separated by a name.
Metaprogramming comes to mind.
According to django.template.loader.BaseLoader:
"A loader may return an already-compiled template instead of the actual
template source. In that case the path returned should be None, since the
path information is associated with the template during the compilation,
which has already been done."
---
We can make the Loader check the file extension as well,
so it will only parse Mustache-compatible files:
.handlebars, .hbs, .mustache, and so on.
This means you can actually keep using the normal Django loaders
too, for other file extensions!
---
The key piece is in django/template/loader.py
def find_template(name, dirs=None):
[...]
for loader in template_source_loaders:
try:
source, display_name = loader(name, dirs)
return (source, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(name)
[...]
Note:
This could still mess up if the custom loader passes
through a Handlebars template with an .html extension.
Later loaders would then throw a fit.
"""
EXTENSIONS = ['.handlebars', '.hbs', '.mustache']
class PystacheAppDirectoriesLoader(app_directories.Loader):
is_usable = True
def load_template(self, template_name, template_dirs=None):
# Only allow certain template types.
filename, extension = os.path.splitext(template_name)
if extension not in EXTENSIONS:
raise TemplateDoesNotExist
source, origin = self.load_template_source(template_name, template_dirs)
template = PystacheTemplate(source)
return template, None
class PystacheFilesystemLoader(filesystem.Loader):
is_usable = True
def load_template(self, template_name, template_dirs=None):
# Only allow certain template types.
filename, extension = os.path.splitext(template_name)
if extension not in EXTENSIONS:
raise TemplateDoesNotExist
source, origin = self.load_template_source(template_name, template_dirs)
template = PystacheTemplate(source)
return template, None
"""
Now update the settings.py file to use the custom Loaders,
putting them ahead of Django's default Loaders in the
TEMPLATE_LOADERS setting.
TEMPLATE_LOADERS = (
'project.templates.PystacheFilesystemLoader',
'project.templates.PystacheAppDirectoriesLoader',
[...]
)
"""
|
Then you can just update the settings.py file to use the custom Loaders, putting them ahead of Django’s default Loaders in the TEMPLATE_LOADERS setting:
1
2
3
4
5
|
TEMPLATE_LOADERS = (
'project.templates.PystacheFilesystemLoader',
'project.templates.PystacheAppDirectoriesLoader',
[...]
)
|
Then if you have, say, a file called index.handlebars somewhere in one of your app directory template/ folders or somewhere else in the TEMPLATE_DIRS list, you can just do this in one of your views:
1
2
|
def someView(request):
return render_to_response('index.handlebars', { 'title': 'Hello, Awesome.' })
|
And all will be good.
Please let me know in the comments if you have any problems with this. (Speed might one of them, I haven’t extensively tested this yet. But I plan to cache these using the Django template cache loader.)
Will this work if you are using template inheritance with an include or block? Or do I need to create a custom template tag? As in:
{% include “_sidebar.mustache” %}
Good question. I never tried that from a Django-style template. It’s worth a shot, if Django does the sensible thing and just loads the included template and passes it the same RequestContext as the initial template, then it could work.
You could also try using partials in the Mustache templates, if that’s an option.
I have to admit that I eventually ported all of my Mustache templates back to Django-style templates. Turns out, view logic in the templates was more sensible than forcing all the logic into views.py, and cut down on a lot of boilerplate code.
The dream of using a single type of templates for both client and server side never seemed to come to fruition for me. And Django threw in a healthy number of WTFs along the way.
Looks like I’m going to have to write a custom template tag that also uses your pystache extension to templating. More of a JavaScript programmer but I’m enjoying Python. Looking at this answer on stackoverflow: http://stackoverflow.com/questions/6451304/django-simple-custom-template-tag-example If you could let me know any of the gotchas along the way that would be much appreciated.
https://github.com/joshbohde/django-backbone-example/blob/master/backbone_example/templates/index.html
Custom template tag mentioned above:
https://gist.github.com/michaelBenin/5752919
This is not just a usefull but also an elegant piece of code.
Thanks for shareing.