RaviTeja
RaviTeja

Reputation: 1026

Using keys() on django template

This is a quick question with the use of dict.keys()

I'm returning a dictionary in py file Ex:

response['dict'] = {'a': [1,2,4], 'b': [5,6,7]}

And in the html i'm try to loop over using keys

{% if dict %}
  {% for list in dict.keys() %}
    list
  {% endfor %}
{endif}

This is throwing an error.

TemplateSyntaxError: Could not parse the remainder: 'keys()' from 'dict.keys()

Need help here. How to use this in Django?

Upvotes: 1

Views: 558

Answers (2)

Matti Lyra
Matti Lyra

Reputation: 13078

It is probably because dict is a reserved keyword in Python. Try

{% if d %}
  {% for key in d.keys() %}
    list
  {% endfor %}
{endif}

or simply

{% if d %}
  {% for key in d %}
    list
  {% endfor %}
{endif}

an iterator over a dictionary in python is by default over the keys so you don't have to specify that you want the keys and not .items() or .values().

Upvotes: -3

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

{% if dict %}
  {% for key, value in dict.items %}
    list
  {% endfor %}
{endif}

edit:

{% if dict %} is not needed - if given context's variable is empty (or if it's empty dict), it silently passes:

  {% for key, value in dict.items %}
    list
  {% endfor %}

Upvotes: 5

Related Questions