python

 
 

Django Render a Context Variable as a Template

I had a small itch to scratch, and I thought it would be fun to write a template tag that renders the passed in parameter as a template with the current pages context.  So for example on a blog or flatpages page, if you used this with the pages content variable, it would render any template tags/filters that is contained in that content.

from django import template
from django.template import TemplateSyntaxError, Variable, Template
from django.utils.translation import ugettext as _

register = template.Library()

class RenderAsTemplate(template.Node):

    def __init__(self, variable):

        self.variable = Variable(variable)

    def render(self, context):

        t = Template(self.variable.resolve(context))

        return t.render(context)


def render_as_template(parser, token):

    bits = list(token.split_contents())

    if len(bits) < 2:
        raise TemplateSyntaxError, _('%r tag requires at least one argument') % bits[0]

    return RenderAsTemplate(bits[1])

render_as_template = register.tag(render_as_template)

As an example you could do something like:

{% load render_as_template %}

.
.
.
{% render_as_template "{% ssi '/path/to/include' %}" %}

and it would actually perform the server side include. It also passes in the context of the page, so if you had a variable called entry.page you could call:

{% render_as_template "{{ entry.page }}" %}

and it would render as the content of the entry.page variable.

 

I passed simple strings to the template tag in the examples above, but you can pass template variables so if you have entry.page and it contained some template tags or filters in it, you could call:

{% render_as_template entry.page %}

and it would render the contents of that variable as a template.

 
 
 
 

Formunculous 2.1.1 Available

Just finished a bugfix release for Formunculous. So feel free to go grab it. Or install it straight from the command line with:

easy_install formunculous

now that it is in the cheese shop.

 

Here is the small list of changes:

  • Now fully compatible with both Django 1.1 and 1.2 (any bugfix release)
  • Word fixes (replacing "Application" with "Form" - legacy problem)
  • Minor HTML and CSS fixes
  • Completed form sorting and paging fixes
 
 
 
 

Formunculous Website Launched

Formunculous Website screenshot

I have been somewhat feverishly working on the design and implementation of a project Website for Formunculous, and I am really quite happy with the results.  I've really been focusing on a visual design and illustration skills as of late, and I thought I would be fun to show off some of those results using a Website I've wanted to create for quite some time.  Let me know what you think.

 
 
Syndicate content