Convert int to ascii [chr()] in django template
-
17-01-2021 - |
Domanda
I am writing a django application, and in a loop,
{% for item in list %}
{{ forloop.counter0 }}
{% endfor %}
this will printout the number in the loop starting from 0. But I want to printout alphabet starting from 'A', so the python way to do it is chr(forloop.counter0+65), but this is inside the template, any ideas? thanks.
Soluzione
You can write a simple custom template tag, for example a filter:
@register.filter(name='chr')
def chr_(value):
return chr(value + 65)
Then load it in your template and you can do:
{{ forloop.counter0|chr }}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow