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?

asked Apr 4, 2022 at 6:35
2
  • Does this answer your question? Django - iterate number in for loop of a template Commented Apr 4, 2022 at 6: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. Commented Apr 4, 2022 at 7:01

1 Answer 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 %}
answered Apr 4, 2022 at 7:55

1 Comment

That should work, but actually it didn't because the variable contains JSON. I explained my question in details there: stackoverflow.com/questions/71736058/… if you can help :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.