Задать вопрос

Тел: +7 965 3737 888

480

Просмотров

2

Ответов

Template range tag

<p>This is a simple tag that I am sure has been written before, but it helps people with the problem, 'how do I iterate through a number in the tempaltes?'.</p>
<p>Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates</p>
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

Вопрос полезен? Да0/Нет0
file_4240.py(1.3Кб)
None

Ответы (2):

Ответztyx:11.01.2013
Ответ полезен? Да0/Нет0

Note that the created range can only be used once in Python 3. It will needl to be wrapped in a list() to be reused.

Ответpenrose:03.03.2009
Ответ полезен? Да0/Нет0

Great tag!

To be able call the tag with dynamic values instead of integer literals, the Variable class can be used (works with Django 1.0):

class RangeNode(Node):
    def __init__(self, num, context_name):
        self.num = Variable(num)
        self.context_name = context_name

    def render(self, context):
        context[self.context_name] = range(int(self.num.resolve(context)))
        return ""