- 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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 4 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago
Comments
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.