- Author:
- justinlilly
- Posted:
- December 5, 2008
- Language:
- Python
- Version:
- 1.0
- Score:
- 1 (after 1 ratings)
a randomized version of {% include %}
{% rand_include "foo.html","bar.html","zot.html" %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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])
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.