from django.template import Library, Node, Variable, TemplateSyntaxError from django.template.loader import get_template register = Library() class RandIncludeNode(Node): def __init__(self, template_names): from random import randrange templates = template_names.split(',') self.template_name = Variable(templates[randrange(len(templates))]) def render(self, context): try: template_name = self.template_name.resolve(context) t = get_template(template_name) return t.render(context) except TemplateSyntaxError, e: if settings.TEMPLATE_DEBUG: raise return '' except: return '' # Fail silently for invalid included templates. @register.tag def rand_include(parser, token): """ Loads a template and renders it with the current context. Example:: {% include "foo/some_include" %} """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0] path = bits[1] return RandIncludeNode(bits[1])