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