blob: 54710f3732ee947c6f5a1890288f748db44bf3e4 [file] [log] [blame]
Scott Baker1dd345e2014-07-07 17:06:07 -07001"""
2Straight Include template tag by @HenrikJoreteg
3
4Django templates don't give us any way to escape template tags.
5
6So if you ever need to include client side templates for ICanHaz.js (or anything else that
7may confuse django's templating engine) You can is this little snippet.
8
9Just use it as you would a normal {% include %} tag. It just won't process the included text.
10
11It assumes your included templates are in you django templates directory.
12
13Usage:
14
15{% load straight_include %}
16
17{% straight_include "my_icanhaz_templates.html" %}
18
19"""
20
21import os
22from django import template
23from django.conf import settings
24
25
26register = template.Library()
27
28
29class StraightIncludeNode(template.Node):
30 def __init__(self, template_path):
31 for template_dir in settings.TEMPLATE_DIRS:
32 self.filepath = '%s/%s' % (template_dir, template_path)
33 if os.path.exists(self.filepath):
34 break
35 else:
36 raise IOError("cannot find %s in %s" % (template_path, str(TEMPLATE_DIRS)))
37
38 def render(self, context):
39 fp = open(self.filepath, 'r')
40 output = fp.read()
41 fp.close()
42 return output
43
44
45def do_straight_include(parser, token):
46 """
47 Loads a template and includes it without processing it
48
49 Example::
50
51 {% straight_include "foo/some_include" %}
52
53 """
54 bits = token.split_contents()
55 if len(bits) != 2:
56 raise template.TemplateSyntaxError("%r tag takes one argument: the location of the file within the template folder" % bits[0])
57 path = bits[1][1:-1]
58
59 return StraightIncludeNode(path)
60
61
62register.tag("straight_include", do_straight_include)