Login

render_as_template template tag

Author:
cogat
Posted:
March 13, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks 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.