user3584455
user3584455

Reputation: 23

Django template - For loop through two values each time

Im working with views and templates.

I've this list in my view

[u'kevinelamo', 50, u'kevin', 4200, u'andres', 200, u'user342', 0, u'cateto', 0]

and I send it to the template..

In the template is parsed like this automatically:

[{"username": "kevinelamo", "time": 50}, {"username": "kevin", "time": 4200}...] 

I want to iterate like this:

{% for username,time in llistat_usuaris %}
<h1>My name is <h1>{{username}}
{{time}}
{% endfor %}

But this gave me one char of the list

My name is
[
My name is
{
My name is
"
My name is
u
My name is
s
My name is
e
My name is
r
My name is
n
My name is
a
My name is
m
My name is
e
My name is

How can I handle it? Thanks

Upvotes: 0

Views: 1848

Answers (1)

dgel
dgel

Reputation: 16796

If you have this list:

l = [u'kevinelamo', 50, u'kevin', 4200, u'andres', 200, u'user342', 0, u'cateto', 0]

You could convert it to a dictionary:

l_dict = dict(zip(l[::2], l[1::2]))

Which will make l_dict:

{u'andres': 200, u'cateto': 0, u'user342': 0, u'kevin': 4200, u'kevinelamo': 50}

Then iterate over key value pairs in your template:

{% for username, time in l_dict.items %}
    <h1>My name is <h1>{{ username }}
    {{ time }}
{% endfor %}

Upvotes: 1

Related Questions