【发布时间】:2021-10-05 03:21:22
【问题描述】:
我有一个带有值列表的字典,基本上每个键都有 10 个值:
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']
}
我正在使用它们在 HTML 中动态生成卡片,因此我需要每张卡片的每个键都有一个值。最终我会得到 10 张卡片。这是我的 HTML 和我最近用 jinja 迭代 dict 的尝试:
{% 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 %}
Jinja sintax 是什么?
【问题讨论】:
-
如何将数据发送到模板?看来您将其转换为字符串,现在您有字符串而不是字典。
-
你有太多的
for-loops。您应该在第一个循环中使用.items()和movies