Login

render_as_template template tag

Author:
cogat
Posted:
March 13, 2009
Language:
Python
Version:
1.0
Tags:
template tag context
Score:
6 (after 7 ratings)

This is a template tag that works like {% include %}, but instead of loading a template from a file, it uses some text from the current context, and renders that as though it were itself a template. This means, amongst other things, that you can use template tags and filters in database fields.

For example, instead of:

{{ flatpage.content }}

you could use:

{% render_as_template flatpage.content %}

Then you can use template tags (such as {% url showprofile user.id %}) in flat pages, stored in the database.

The template is rendered with the current context.

Warning - only allow trusted users to edit content that gets rendered with this tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django import template
from django.template import Template, Variable, TemplateSyntaxError

register = template.Library()

class RenderAsTemplateNode(template.Node):
    def __init__(self, item_to_be_rendered):
        self.item_to_be_rendered = Variable(item_to_be_rendered)

    def render(self, context):
        try:
            actual_item = self.item_to_be_rendered.resolve(context)
            return Template(actual_item).render(context)
        except template.VariableDoesNotExist:
            return ''

def render_as_template(parser, token):
    bits = token.split_contents()
    if len(bits) !=2:
        raise TemplateSyntaxError("'%s' takes only one argument"
                                  " (a variable representing a template to render)" % bits[0])    
    return RenderAsTemplateNode(bits[1])

render_as_template = register.tag(render_as_template)

More like this

  1. "Partial Templates" - an alternative to "include" by vigrid 6 years, 1 month ago
  2. render_to by asolovyov 6 years, 9 months ago
  3. Allow template tags in a Flatpage's content by kylefox 6 years, 8 months ago
  4. template tag for highlighting currently active page by adunar 6 years, 5 months ago
  5. Partial templates, combine with and include by koblas 4 years, 11 months ago

Comments

dan90 (on May 9, 2009):

Nice! one comment I would add for other venturers down this path is - don't forget that, should you wish to markup your string with template markup employing your own custom template tags and filters, your string must start with a standard django {% load library %} thing. otherwise you only get the django built-ins.

#

Please login first before commenting.