Skip to content

Instantly share code, notes, and snippets.

@Glench
Created June 15, 2012 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Glench/2934727 to your computer and use it in GitHub Desktop.
Save Glench/2934727 to your computer and use it in GitHub Desktop.
Better Django include_raw, for escaping included files in templates
# 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