Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask Basics Character Builder Loop Nested Items

Y B
Y B
14,136 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,136 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,136 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.