0

I have trouble getting the middle loop in a forloop in django template.

I've tried using

{% for value in key.dictionary %}
    {% if forloop.counter == widthratio value|length 2 1 %}

but with no effect. Actually after the widthratio I get an error Expected %}

Computing the division was taken from this post Is there a filter for divide for Django Template?

1 Answers1

1

widthratio is not a filter, it's a tag. But you can assign the result of widthratio to a variable using as:

{% widthratio key.dictionary|length 2 1 as midpoint %}
{% for key, value in key.dictionary.items %}
    {% if forloop.counter == midpoint|add:"0" %}

widthratio produces a string, so in order to test equal with an integer forloop.counter value, we have to convert midpoint back to an integer too, using the add filter as a work-around.

Note that we take the length of the dictionary, not of a single key. I also opted to loop over the dictionary items (key and value) in the above example.

Demo:

>>> from django.template import Context, Template
>>> t = Template("""\
... {% widthratio foo|length 2 1 as midpoint %}
... {% for key, value in foo.items %}
...     {% if forloop.counter = midpoint|add:"0" %}Half-way through!{% endif %}
...     {{ forloop.counter }}: {{ key }} == {{ value }}
... {% endfor %}
... """)
>>> context = Context({"foo": {"spam": 42, "vikings": 17, "eggs": 81}})
>>> print(t.render(context))



    1: spam == 42

    Half-way through!
    2: vikings == 17


    3: eggs == 81
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343