[Answered ]-How to assemble a variable name in Django templating language?

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 %}

Leave a comment