blob: a3b3b2a0d3e696b7b5256e2c9da877f5b3a2c7d9 [file] [log] [blame]
Scott Baker1dd345e2014-07-07 17:06:07 -07001from django import template
2from django.conf import settings
3import pystache
4import os
5
6register = template.Library()
7
8class View(pystache.View):
9 template_path = settings.TEMPLATE_DIRS[0]
10
11 def __init__(self, template_dir, template_name, context):
12 self.template_path = template_dir
13 self.template_name = template_name
14 return super(View, self).__init__(context=context)
15
16class MustacheNode(template.Node):
17 def __init__(self, template_name, attr=None):
18 for template_dir in settings.TEMPLATE_DIRS:
19 if os.path.exists(os.path.join(template_dir, template_name) + ".mustache"):
20 break
21 else:
22 raise IOError("failed to find %s in %s" % (template_name, str(settings.TEMPLATE_DIRS)))
23
24 self.template_path = template_dir
25 self.template = template_name
26 self.attr = attr
27
28 def render(self, context):
29 mcontext = context[self.attr] if self.attr else {}
30 view = View(self.template_path, self.template, context=mcontext)
31 return view.render()
32
33def do_mustache(parser, token):
34 """
35 Loads a mustache template and render it inline
36
37 Example::
38
39 {% mustache "foo/bar" data %}
40
41 """
42 bits = token.split_contents()
43 if len(bits) not in [2,3]:
44 raise template.TemplateSyntaxError("%r tag takes two arguments: the location of the template file, and the template context" % bits[0])
45 path = bits[1]
46 path = path[1:-1]
47 attrs = bits[2:]
48 return MustacheNode(path, *attrs)
49
50
51register.tag("mustache", do_mustache)