How to assemble a variable name in Django templating language?


I am trying to assemble a variable in Django template in that way:
obj.length.forloop.counter where the foorloop.counter should return the number.
for example obj.length.1 then obj.length.2 and so on…

I tried the add filter:
obj.length|add:forloop.counter but that returned nothing at all.
Is there any way that I can assemble variable names like that in django templating language?


You might register a custom filter (cf. documentation) to achieve what you want:

def get(obj, attr):
    if hasattr(obj, attr):
        return getattr(obj, attr)
    return obj[attr]

You could then use it like that in your template:

{{ obj.length|get:forloop.counter }}

This being said, I wonder if you could not directly iterate obj or obj.length itself. Are you sure you cannot do something like that in your template? That would be much cleaner.

{% for item in obj %}
    {% comment %}Do something with item{% endcomment %}
{% endfor %}

Answered By – scÅ«riolus

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published