Django Render a Context Variable as a Template

 
 
PDF versionPDF version

I had a small itch to scratch, and I thought it would be fun to write a template tag that renders the passed in parameter as a template with the current pages context.  So for example on a blog or flatpages page, if you used this with the pages content variable, it would render any template tags/filters that is contained in that content.

from django import template
from django.template import TemplateSyntaxError, Variable, Template
from django.utils.translation import ugettext as _

register = template.Library()

class RenderAsTemplate(template.Node):

    def __init__(self, variable):

        self.variable = Variable(variable)

    def render(self, context):

        t = Template(self.variable.resolve(context))

        return t.render(context)


def render_as_template(parser, token):

    bits = list(token.split_contents())

    if len(bits) < 2:
        raise TemplateSyntaxError, _('%r tag requires at least one argument') % bits[0]

    return RenderAsTemplate(bits[1])

render_as_template = register.tag(render_as_template)

As an example you could do something like:

{% load render_as_template %}

.
.
.
{% render_as_template "{% ssi '/path/to/include' %}" %}

and it would actually perform the server side include. It also passes in the context of the page, so if you had a variable called entry.page you could call:

{% render_as_template "{{ entry.page }}" %}

and it would render as the content of the entry.page variable.

 

I passed simple strings to the template tag in the examples above, but you can pass template variables so if you have entry.page and it contained some template tags or filters in it, you could call:

{% render_as_template entry.page %}

and it would render the contents of that variable as a template.

 
 

Comments

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.