Scott Baker | 1dd345e | 2014-07-07 17:06:07 -0700 | [diff] [blame] | 1 | """ |
| 2 | Straight Include template tag by @HenrikJoreteg |
| 3 | |
| 4 | Django templates don't give us any way to escape template tags. |
| 5 | |
| 6 | So if you ever need to include client side templates for ICanHaz.js (or anything else that |
| 7 | may confuse django's templating engine) You can is this little snippet. |
| 8 | |
| 9 | Just use it as you would a normal {% include %} tag. It just won't process the included text. |
| 10 | |
| 11 | It assumes your included templates are in you django templates directory. |
| 12 | |
| 13 | Usage: |
| 14 | |
| 15 | {% load straight_include %} |
| 16 | |
| 17 | {% straight_include "my_icanhaz_templates.html" %} |
| 18 | |
| 19 | """ |
| 20 | |
| 21 | import os |
| 22 | from django import template |
| 23 | from django.conf import settings |
| 24 | |
| 25 | |
| 26 | register = template.Library() |
| 27 | |
| 28 | |
| 29 | class 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 | |
| 45 | def 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 | |
| 62 | register.tag("straight_include", do_straight_include) |