[Fixed]-Change List in Embedded For Loop in Django Template

1👍

Why don’t you do the work in the view instead of trying to come up with something complicated in the template?

For example, in your Python:

names = ['apple', 'orange', 'carrot']
colors = [ ['red', 'green'], ['orange', 'red'], ['orange', 'yellow'] ]
fruits = zip(names, colors)

And then in your template:

{% for name, colors in fruits %}
  <div>
  {{ name }} -
  {% for color in colors %}
    {{ color }}
  {% endfor %}
  </div> 
{% endfor %}

0👍

If I understand you correctly, what you want to do is something like form[matrix_row]

{% for matrix_row in request.session.matrix_rows %}
    {% for radio in form[matrix_row] %}
       <li>{{ radio }}</li>
    ...

That isn’t possible in Django templates, so you would need to add your own simple templatetag for that. Something like this

@register.filter
def keyvalue(dic, key):
    """Use a variable as a dictionary key"""
    return dic[key]

And now you can do

{% for matrix_row in request.session.matrix_rows %}
    {% for radio in form|keyvalue:matrix_row %}
       <li>{{ radio }}</li>
    ...
👤C14L

Leave a comment