1

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?

  • Does this answer your question? [Django - iterate number in for loop of a template](https://stackoverflow.com/questions/11481499/django-iterate-number-in-for-loop-of-a-template) – michjnich Apr 04 '22 at 06:56
  • @michjnich No, what I am trying to do is `obj.length.1` , then `obj.length.2` so I want that value of 1 or 2 to be appended to the variable name itself then to get the value of that variable. – Youssef Ihab Apr 04 '22 at 07:01

1 Answers1

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 %}
scūriolus
  • 657
  • 2
  • 5
  • 15
  • That should work, but actually it didn't because the variable contains JSON. I explained my question in details there: https://stackoverflow.com/questions/71736058/how-to-assemble-the-variable-name-to-use-data-from-jsonfield-inside-the-template if you can help :) – Youssef Ihab Apr 04 '22 at 14:43