Manish
Manish

Reputation: 3521

How to parse a nested dictionary with Jinja2

I am passing a dictionary to template in python

   users={
        "output": {
                "title": "Sample Konfabulator Widget"
        }
    }

    return render_template('user.html', **locals())

but i can not parse the output at response page(user.html).

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Users</h1>
    <p class="important">
      <ul>
      {% for user in users %}
          <li>{{user}}.title</a></li>
      {% endfor %}
      </ul>

    </p>
{% endblock %}

But i don't get expected output Sample Konfabulator Widget while i get output.title. How can i get value of output.title?

Upvotes: 1

Views: 2427

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191701

users is a one-element dictionary, not a list, so a loop doesn't really make sense.

Since you have just one element, get that without a loop

<p>{{users['output']['title']}}</p>

If you did want multiple "users", and had an element like this

users={
    "output": {
            "title": "Sample Konfabulator Widget"
    }, 
    "output2": {
            "title": "foo"
    }
}

Then you could have done a loop

  {% for key in users %}
      <li>{{key}} : {{users[key]['title']}}</li>
  {% endfor %}

Upvotes: 4

Related Questions