代码之家  ›  专栏  ›  技术社区  ›  slacy

在Django模板中访问并行阵列?

  •  5
  • slacy  · 技术社区  · 15 年前

    我的视图代码基本上如下所示:

    context = Context() 
    context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f']
    context['other_values'] = [4, 8, 15, 16, 23, 42]
    

    我希望我的模板代码如下所示:

    {% for some in some_values %} 
      {% with index as forloop.counter0 %} 
        {{ some }} : {{ other_values.index }} <br/> 
      {% endwith %} 
    {% endfor %} 
    

    我预计这将产生:

    a : 4 <br/> 
    b : 8 <br/> 
    c : 15 <br/> 
    d : 16 <br/> 
    e : 23 <br/> 
    f : 42 <br/> 
    

    1 回复  |  直到 15 年前
        1
  •  8
  •   Daniel Roseman    15 年前

    zip(some_values, other_values) ,然后在模板中使用它

    from itertools import izip
    some_values = ['a', 'b', 'c', 'd', 'e', 'f']
    other_values = [4, 8, 15, 16, 23, 42]
    context['zipped_values'] = izip(some_values, other_values)
    
    {% for some, other in zipped_values %}
        {{ some }}: {{ other }}  <br/>
    {% endfor %}