Algorithmatic
Algorithmatic

Reputation: 1892

How to get object attribute in django template for loop

How can you do the Django template equivalent to this python for loop?

    extra_context = [o.extra_context for o in activities] 

or do I need to register a new template tag?

Upvotes: 0

Views: 1660

Answers (2)

Algorithmatic
Algorithmatic

Reputation: 1892

After looking around and reading some documentation, here's my approach

{% for a in activities %}
    {% with a.extra_context as o %}
    {% endwith %}
{% endfor %} 

Upvotes: 0

souldeux
souldeux

Reputation: 3755

If you want to create a new list variable to iterate over, you need access to the template's context - which I don't think you can do from the template itself. As far as I know that must be done from the view. This question may provide more insight. The discussion of template tags found in the same thread is also relevant.

If activities is the only thing being passed through the request context, then I believe the closest thing you can do from within the template without registering a new tag is:

{% for o in activities %}
    {{ o.extra_context }}
    <!-- do stuff -- >
{% endfor %}

I would refer to the above-linked thread for discussion on making a tag that can work with a new list, etc.

Upvotes: 1

Related Questions