'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?



Solution 1:[1]

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

@register.filter()
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 %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sc?riolus