Created
March 25, 2014 19:42
-
-
Save xXPhenomXx/9769684 to your computer and use it in GitHub Desktop.
An incrementing Django template tag that can be used for things like Quantity inputs, etc...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RangeNode(Node): | |
def __init__(self, num, context_name): | |
self.num, self.context_name = num, context_name | |
def render(self, context): | |
context[self.context_name] = range(int(self.num)) | |
return "" | |
@register.tag | |
def num_range(parser, token): | |
""" | |
Takes a number and iterates and returns a range (list) that can be | |
iterated through in templates | |
Syntax: | |
{% num_range 5 as some_range %} | |
{% for i in some_range %} | |
{{ i }}: Something I want to repeat\n | |
{% endfor %} | |
Produces: | |
0: Something I want to repeat | |
1: Something I want to repeat | |
2: Something I want to repeat | |
3: Something I want to repeat | |
4: Something I want to repeat | |
""" | |
try: | |
fnctn, num, trash, context_name = token.split_contents() | |
except ValueError: | |
raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\ | |
as context_variable" % (fnctn, fnctn) | |
if not trash == 'as': | |
raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\ | |
as context_variable" % (fnctn, fnctn) | |
return RangeNode(num, context_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment