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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months 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.