Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop with range in django template

How can i make a for loop with range function in django template?
i want to search in three lists by using this structure.

I tried this and it didn’t work:

{% for i in range(number) %}
    {{ my_list.i }}
{% endfor %}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot simply use use Pythonic round brackets inside curly brackets. Also, it’s not that simple to get from dict using variable.
You can try creating a custom templatetags.

Create file in your app: "your_project/your_app/templatetags/custom_tags.py" (and empty "__init__.py" in the same folder):

from django import template

register = template.Library()

@register.filter(name='get_range') 
def get_range(number):
    return range(number)

@register.filter(name='get_from_dict') 
def get_from_dict(my_dict, i):
    return my_dict.get(i, None)

And then in template:

{% load custom_tags %}

{% for i in number|get_range %}
    {{ my_list|get_from_dict:i }}
{% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading