【问题标题】:Numeric for loop in Django templates with Context Variable带有上下文变量的 Django 模板中的数字 for 循环
【发布时间】:2015-03-20 17:26:28
【问题描述】:

我想在 Django 模板中做一个 Numeric for Loop。经过一番搜索,我发现了一个非常不错的sn-p: https://djangosnippets.org/snippets/779/

有了它我可以做到

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

但是,我似乎只能在 {% num_range %} 标签上使用一个数字(例如,这里是 5)。

问题是我在“5”的位置使用什么上下文变量。假设我有一个上下文 {{times}},它是一个整数变量。我该怎么做这样的事情:

{% num_range times as some_range %}

然后在 {% for %} 标签中使用“some_range”?

【问题讨论】:

    标签: django templates for-loop


    【解决方案1】:

    我没有对此进行测试,但我认为它应该可以工作。尝试在 sn-p 中的 RangeNode 类下替换它:

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

    有了这个

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

    【讨论】:

    • 谢谢!但我收到了一个 KeyError。根据回溯,它似乎发生在num = int(context[self.num]),但我不确定。
    猜你喜欢
    • 2018-11-17
    • 2017-03-07
    • 2010-11-09
    • 2012-03-28
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多