1

I have a dict with a list of values, basically each key has 10 values:

movies = {
'title': ['The Shawshank Redemption', 'The Godfather', ..., 'The Lord of the Rings: The Fellowship of the Ring'],
'year': ['1994', '1972', ..., '2001'],
'poster': ['url', 'url1', ..., 'url9'],
'rating': ['9.2', '9.1', ..., '8.8'],
'votes': ['2467733', '1705796', ..., '1732916']
}

I'm using them to dinamicaly generate cards in HTML so I need every card to have one value of each key. Ultimately I'll end up with 10 cards. Here's my HTML and my latest attempt to iterate the dict with jinja:

{% for movie in movies %}
    {% for key, value in movie.items() %} <!-- This line is raising an error: jinja2.exceptions.UndefinedError: 'str object' has no attribute 'items' -->
        {% for value in key %}
            <div class="col-md-3">
                <div class="card" style="width: 15rem;">
                    <img src="{{ value.poster }}" class="card-img-top" alt="Movie Poster">
                    <div class="card-body">
                      <h5 class="card-title">{{ value.title }}</h5>
                      <p class="card-text">Release year: {{ value.year }}</p>
                    </div>
                    <ul class="list-group list-group-flush">
                      <li class="list-group-item">Rating: {{ value.rating }} - ({{ value.votes }} Votes)</li>
                    </ul>
                    <div class="card-body">
                     <a href="#" class="card-link">More</a>
                    </div>
                </div>
            </div>
         {% endfor %}
     {% endfor %}
 {% endfor %}

What is the Jinja sintax to do it?

1 Answer 1

2

It's not jinja syntax, it's python syntax. for movie in movies: iterates over the members (keys) of movies, thus movie is a string.

Contemplate how creating movies as a list of dictionaries, one dictionary per movie, (think stock holdings in finance?) would significantly simplify the code.

Also consider testing the loops/outputs in command line python3 to speed up the process of attaining the desired result.

1
  • Actually, the data I receive from the API call is a list of dictionaries, one for each movie, and that's what I was trying to use but I was only getting the first movie in the iteration. I thought with one dictionary would be easier, but it's not. I'll give it another shot. Oct 4, 2021 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .