- Author:
- skarphace
- Posted:
- September 9, 2011
- Language:
- Python
- Version:
- 1.3
- Score:
- 0 (after 0 ratings)
This template tag will duplicate its contents according to a variable or integer supplied to it.
{% duplicate 3 %}a{% endduplicate %}
This would return:
aaa
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 | from django import template
register = template.Library()
@register.tag
def duplicate(parser, token):
nodelist = parser.parse(('endduplicate',))
parser.delete_first_token()
try:
tag_name, repeat = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires exactly one arguments" % token.contents.split()[0])
return DuplicateNode(nodelist, repeat)
class DuplicateNode(template.Node):
def __init__(self, nodelist, repeat):
self.nodelist = nodelist
self.repeat = repeat
def render(self, context):
try:
repeat = int(self.repeat)
except ValueError:
self.repeat = template.Variable(self.repeat)
repeat = self.repeat.resolve(context)
output = ''
i = 0
while i < repeat:
output = output + self.nodelist.render(context)
i = i + 1
return output
|
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.