from django import template
from django.utils.safestring import mark_safe
register = template.Library()
class RenderNode(template.Node):
def __init__(self, content):
self.content = content
def render(self, context):
try:
self.content = template.resolve_variable(self.content, context)
return template.Template(self.content).render(template.Context(context, autoescape=False))
except template.TemplateSyntaxError, e:
return mark_safe("<strong>Template error: There is an error one of this page's template tags: <code>%s</code></small>" % e.message)
@register.tag(name='render')
def render_django(parser, token):
" Example: {% render flatpage.content %}"
content = token.split_contents()[-1]
return RenderNode(content)
render_django.is_safe = True
Comments
Please have a look at the django-dbtemplates project that enables you to save templates in the database in an official way and uses an own template loader.
#
@jezdez dbtemplates doesn't seem to address what kylefox is doing here, which is to allow use of templatetags in flatpages. Which seems more useful than just storing templates in the db (why bother?)... if you have to go through making view stubs for your templates then you lose the shortcut benefit of flatpages.
nice handy snippet, something like this should be part of flatpages!
#
I had to make one small modification to this so that it would work within a loop:
In render, rather than reassigning to "self.content", I just use a local "content" variable. Otherwise I get some nasty huge TemplateSyntaxError.
Now I can use, for example:
Otherwise works great; I'm using this extensively in my sites. Thank you!
#
Slightly updated the code (using template.Variable() instead of deprecated resolve_variable()).
I also applied @Tarken's fix (using local "content").
Feedback? Worth re-posting here on DjangoSnippets? Perhaps not, but I thought I would share my code in the hopes that is saves others time in the future.
#