Python Flask Basics Character Builder Loop Nested Items

Y B
Y B
14,135 Points

Can't pass flask loop challenge

I can't get past the flask loop challenge. It keeps saying can't find the right number of <li> items (0). Not sure why?

flask_app.py
from flask import Flask, render_template

from teachers import TEACHERS

app = Flask(__name__)


@app.route('/')
def index():
    return render_template("teachers.html", teachers=TEACHERS)
templates/teachers.html
<ul class="teachers">
  {% for item in teachers[name] %}
  <li>
    <h2>{{ teachers[name] }}</h2>
  </li>
  {% endfor %}
</ul>

2 Answers

Ryan Merritt
Ryan Merritt
5,789 Points

Jinja2 allows you to access attributes of objects in two ways:

{{ foo.bar }}

or

{{ foo['bar'] }}

The name attribute in your for loop should be surrounded by quotes like this:

{% for item in teachers['name'] %}

Additionally, remember to use the variable you set inside the forloop. You set a variable named item to represent each value found in teachers['name'] so instead of using {{ teachers['name'] }} inside the header tag, try item.

{% for item in teachers['name'] %}
    <li>
        <h2>{{ item }}</h2>
    </li>
{% endfor %}

Let me know if there are any further issues. Good luck!

Y B
Y B
14,135 Points

Thanks but I still get an error: 'Didn't find the right number of <li>'s found 0'

<ul class="teachers">
{% for item in teachers['name'] %}
    <li>
        <h2>{{ item }}</h2>
    </li>
{% endfor %}

</ul>
Ryan Merritt
Ryan Merritt
5,789 Points

Ahhhh teachers is some kind of iterable of objects, each having a 'name' attribute, meaning that you should loops through teachers and access 'name' for each item.

<ul class="teachers">
{% for teacher in teachers %}
  <li><h2>{{ teacher['name'] }}</h2></li>
{% endfor %}
</ul>
Y B
Y B
14,135 Points

Thanks that worked. Shame they couldn't have just shown us what teachers is.

Ryan Merritt
Ryan Merritt
5,789 Points

Depending on the challenge you can print the object to see what it says. Occasionally the "bummer" response will say, "Got x instead of y." showing you the contents of what you printed.