| 1 | from django.conf import settings |
| 2 | from django.template import Library, Node, Template, TemplateSyntaxError |
| 3 | from django.template.defaulttags import include_is_allowed |
| 4 | |
| 5 | |
| 6 | register = Library() |
| 7 | |
| 8 | |
| 9 | class SsiNode(Node): |
| 10 | def __init__(self, filepath, parsed): |
| 11 | self.filepath, self.parsed = filepath, parsed |
| 12 | |
| 13 | def render(self, context): |
| 14 | filepath = self.filepath.resolve(context) |
| 15 | if not include_is_allowed(filepath): |
| 16 | if settings.DEBUG: |
| 17 | return "[Didn't have permission to include file]" |
| 18 | else: |
| 19 | return '' # Fail silently for invalid includes. |
| 20 | try: |
| 21 | fp = open(filepath, 'r') |
| 22 | output = fp.read() |
| 23 | fp.close() |
| 24 | except IOError: |
| 25 | output = '' |
| 26 | if self.parsed: |
| 27 | try: |
| 28 | t = Template(output, name=filepath) |
| 29 | return t.render(context) |
| 30 | except TemplateSyntaxError, e: |
| 31 | if settings.DEBUG: |
| 32 | return "[Included template had syntax error: %s]" % e |
| 33 | else: |
| 34 | return '' # Fail silently for invalid included templates. |
| 35 | return output |
| 36 | |
| 37 | |
| 38 | def ssi(parser, token): |
| 39 | """ |
| 40 | Outputs the contents of a given file into the page. |
| 41 | |
| 42 | Like a simple "include" tag, the ``ssi`` tag includes the contents |
| 43 | of another file -- which must be specified using an absolute path -- |
| 44 | in the current page:: |
| 45 | |
| 46 | {% ssi "/home/html/ljworld.com/includes/right_generic.html" %} |
| 47 | |
| 48 | If the optional "parsed" parameter is given, the contents of the included |
| 49 | file are evaluated as template code, with the current context:: |
| 50 | |
| 51 | {% ssi "/home/html/ljworld.com/includes/right_generic.html" parsed %} |
| 52 | """ |
| 53 | bits = token.contents.split() |
| 54 | parsed = False |
| 55 | if len(bits) not in (2, 3): |
| 56 | raise TemplateSyntaxError("'ssi' tag takes one argument: the path to" |
| 57 | " the file to be included") |
| 58 | if len(bits) == 3: |
| 59 | if bits[2] == 'parsed': |
| 60 | parsed = True |
| 61 | else: |
| 62 | raise TemplateSyntaxError("Second (optional) argument to %s tag" |
| 63 | " must be 'parsed'" % bits[0]) |
| 64 | filepath = parser.compile_filter(bits[1]) |
| 65 | return SsiNode(filepath, parsed) |
| 66 | ssi = register.tag(ssi) |