render_as_template template 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. Row-Level, URL-based permissions for FlatPages by bradmontgomery 3 years, 11 months ago
  2. Use MEDIA_URL in flatpages with SSL by gobble 2 years, 10 months ago
  3. FieldsetForm by Ciantic 6 years, 1 month ago
  4. A GET string modifier templatetag by cogat 4 years, 5 months ago
  5. Allow template tags in a Flatpage's content by kylefox 4 years, 10 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.

#

(Forgotten your password?)