Joe
Joe

Reputation: 26777

Having problems iterating over dict in Django template

There seem to be a million questions (and answers) about this, but none of them are working for me.

I've got something like this:

test_dict = {'name':'Joe'}
return render_to_response('home.html',test_dict,context_instance=RequestContext(request))

In the template, I'm trying to do this:

{% for k,v in test_dict.items %}
  Hello {{ v }} <br />
{% endfor %}

But no luck. On the other hand, this works:

Hello {{ name }}

(No for loop). I must be missing something really obvious?

EDIT
In response to the first answer, I've also tried this:

test_dict = {'name':'Joe'}
data = {'test_dict':test_dict}

return render_to_response('home.html',data,context_instance=RequestContext(request))

And in the template:

{% block content %}
  {% for k, v in data.items %}
    Hello {{ v }} <br />
  {% endfor %}
{% endblock %}

Still nothing showing up.

Upvotes: 2

Views: 1319

Answers (2)

niko.makela
niko.makela

Reputation: 547

When:

test_dict = {'name':'Joe'}
data = {'test_dict':test_dict}

return render_to_response('home.html',data,context_instance=RequestContext(request))

Use:

{% for k, v in test_dict.items %}

Upvotes: 0

sberry
sberry

Reputation: 132018

To do what you want, you would want something like

data = {'test_dict':test_dict}
return render_to_response('home.html',data,context_instance=RequestContext(request))

From the docs

A dictionary of values to add to the template context.

So in your example, test_dict is injected into the template context. Think of it working like this:

template = Template()
for k, v in dictionary.items():
    template[k] = v

So test_dict is not injected into the template's context, but the keys and values of test_dict are.

Upvotes: 2

Related Questions