A
A
Artyom Innokentiev2016-01-17 00:25:01
Django
Artyom Innokentiev, 2016-01-17 00:25:01

How to loop through the attributes of an object in a template?

The bar object with attributes attr1 , attr2 , attr3 , attr4 is passed to the template .
You need to wrap the value of each attribute in a div:

<div class="hello">
    {{ bar.attr1 }}
</div>
<div class="hello">
    {{ bar.attr2 }}
</div>
<div class="hello">
    {{ bar.attr3 }}
</div>
<div class="hello">
    {{ bar.attr4 }}
</div>

How to do it in a shorter and simpler way - for example in a loop (ideally, something as simple as this):
{% for item in bar %}
    {{ item }}
{% endfor %}

Or form a list of fields in the view and loop through it:
bar_attrs = ["attr1", "attr2", "attr3", "attr4"]

{% for attr in bar_attrs %}
    {{ getattr(bar, attr) }}
{% endfor %}

How to make it beautiful and short?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Innokentiev, 2016-01-17
@artinnok

views.py:

bar_attrs = ["attr1", "attr2", "attr3", "attr4"]
context['bar_vals'] = [getattr(bar, i) for i in bar_attrs]

{% for item in bar_vals %}
    <div class="hello">
        {{ item }}
    </div>
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question