Accepts the same arguments as the 'range' builtin and creates
a list containing the result of 'range'.
Syntax:
{% mkrange [start,] stop[, step] as context_name %}
For example:
{% mkrange 5 10 2 as some_range %}
{% for i in some_range %}
{{ i }}: Something I want to repeat\n
{% endfor %}
Produces:
5: Something I want to repeat
7: Something I want to repeat
9: Something I want to repeat
# based on: http://www.djangosnippets.org/snippets/779/fromdjango.templateimportLibrary,Node,TemplateSyntaxErrorregister=Library()classRangeNode(Node):def__init__(self,range_args,context_name):self.range_args=range_argsself.context_name=context_namedefrender(self,context):context[self.context_name]=range(*self.range_args)return""@register.tagdefmkrange(parser,token):""" Accepts the same arguments as the 'range' builtin and creates a list containing the result of 'range'. Syntax: {% mkrange [start,] stop[, step] as context_name %} For example: {% mkrange 5 10 2 as some_range %} {% for i in some_range %} {{ i }}: Something I want to repeat\n {% endfor %} Produces: 5: Something I want to repeat 7: Something I want to repeat 9: Something I want to repeat """tokens=token.split_contents()fnctl=tokens.pop(0)deferror():raiseTemplateSyntaxError,"%s accepts the syntax: {%%%s [start,] "+\
"stop[, step] as context_name %%}, where 'start', 'stop' "+\
"and 'step' must all be integers."%(fnctl,fnctl)range_args=[]whileTrue:iflen(tokens)<2:error()token=tokens.pop(0)iftoken=="as":breakifnottoken.isdigit():error()range_args.append(int(token))iflen(tokens)!=1:error()context_name=tokens.pop()returnRangeNode(range_args,context_name)
Comments
Hi wolever, thanks for this snippet I think this should be a built-in.
I'm trying to create a range but using template variables instead of number literals, but it fails parsing the expression.
"TypeError - not all arguments converted during string formatting"
Does mkrange just support number literals? or am I doing something wrong?
Thanks a lot.
#
Please login first before commenting.