Delremm
Delremm

Reputation: 3161

Django templates, how to make a list of item's values from list of items

I have list of items:

items = [item1, item2, ...] where

item1 = {'name': 'item1', 'value': 1} and so on.

In templates i have a list of these items: {{ items }}

How can i get a list [item1.name, item2.name, ...] in templates?

Upvotes: 0

Views: 338

Answers (3)

Luan Fonseca
Luan Fonseca

Reputation: 1517

You can iterate over the items like that, in a for:

{% for item in items %}
    <p>Name: {{ item.name }}</p>
    <p>Value: {{ item.value }}</p>
{% endfor %}

You can't "create" variables in the Django Template Engine, but you can do it in your View: items_names = [x['name'] for x in items]

And then access the items_names in your template.

Upvotes: 0

crossin
crossin

Reputation: 113

If your just want to iterate the names in items:

{% for item in items %}
<p>name: {{item.name}}</p>
{% endfor %}

Upvotes: 0

Ngenator
Ngenator

Reputation: 11259

In your view, just add .values_list('name', flat=True) to your queryset. Now you are passing a list of item names to your template.

Other options:

  • Use a for loop to iterate over items.
  • Make a custom template tag.

Upvotes: 1

Related Questions