Scott Baker | 1dd345e | 2014-07-07 17:06:07 -0700 | [diff] [blame] | 1 | from django import template |
| 2 | from django.conf import settings |
| 3 | import pystache |
| 4 | import os |
| 5 | |
| 6 | register = template.Library() |
| 7 | |
| 8 | class 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 | |
| 16 | class 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 | |
| 33 | def 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 | |
| 51 | register.tag("mustache", do_mustache) |