首页 > 解决方案 > 在 Jinja2 中获取错误的值

问题描述

我在 Django 中将字典从 python 传递到我的 HTML,然后我想获取特定键的值。我在 for 循环中传递字典,然后使用 if 语句搜索键。如果找到该键,则打印该值。

以下是通过的字典:

{
    'id': 1, 
    'book': {
        'isbn': '0439554934', 
        'isbn13': '9780439554930', 
        'title': "Harry Potter and the Sorcerer's Stone (Harry Potter, #1)",
        'publisher': 'Scholastic Inc', 
        'publishYear': 1997, 
        'publishMonth': 6, 
        'edition': None, 
        'rating': '4.46', 
        'popularity': 25779963, 
        'authors': ['J.K. Rowling'], 
        'genres': ['fiction', 'fantasy', 'young-adult']
    }, 
    'userID': 1, 
    'price': '10.00', 
    'condition': 'New', 
    'image1': '', 
    'image2': '', 
    'image3': '', 
    'image4': '', 
    'image5': '', 
    'comment': ''
}

然后我想得到这本书的标题,所以下面是我的代码:

  {% for key, value in book.items %}
      {% if value.title %}
        <h3> {{value.title}}</h3>
      {% endif %}
  {% endfor %}

但是,我不仅获得了标题,还获得了打印的价格和条件。有人可以让我知道我做错了什么吗?

标签: pythonhtmldjangojinja2

解决方案


推荐阅读