Created
June 15, 2012 04:52
-
-
Save Glench/2934727 to your computer and use it in GitHub Desktop.
Better Django include_raw, for escaping included files in templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To make this work, put this file in the templatetags directory of your app | |
# (make it if it doesn't exist, and make sure to add a blank __init__.py file | |
# if it doesn't already exist). Then from your template call | |
# {% load include_raw %} {% include_raw 'some_template' %} | |
from django import template | |
from django.conf import settings | |
from django.template.loaders.app_directories import load_template_source | |
register = template.Library() | |
def do_include_raw(parser, token): | |
""" | |
Performs a template include without parsing the context, just dumps the template in. | |
""" | |
try: | |
tag_name, template_name = token.split_contents() | |
except ValueError: | |
raise template.base.TemplateSyntaxError, "include_raw tag takes one argument: the name of the template to be included" | |
if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]: | |
template_name = template_name[1:-1] | |
return IncludeRawNode(template_name) | |
class IncludeRawNode(template.Node): | |
def __init__(self, template_name): | |
self.template_name = template_name | |
def render(self, context): | |
try: | |
template_var = template.Variable(self.template_name) | |
template_name = template_var.resolve(context) | |
source, path = load_template_source(template_name, settings.TEMPLATE_DIRS) | |
return source | |
except template.VariableDoesNotExist: | |
source, path = load_template_source(self.template_name, settings.TEMPLATE_DIRS) | |
return source | |
register.tag("include_raw", do_include_raw) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment