【问题标题】:python dictionary value is getting printed on a line but not getting printed on another line in djangopython字典值打印在一行上,但没有打印在django的另一行上
【发布时间】:2021-09-28 09:32:36
【问题描述】:

我是 django 新手,使用 python 3.8 版

在我的 index.html 中,我尝试使用 for 循环显示产品及其信息,如下所示:

{% for prod in products %}
<footer class="card-footer">
    <span id="atc_prod_{{ prod.product_id }}" class="atc_prod">prod_{{ prod.product_id }}
    <button class="button is-info is-small card-footer-item cart" id="prod_{{ prod.product_id }}">Add to Cart</button>
    </span>
    <a href="/shop/products/{{ prod.product_id }}"><button class="button is-small is-info card-footer-item cart" id="qv{{ prod.product_id }}">Quick View</button></a>
</footer>
{% endfor %}

产品列表结构如下:

products = [
    {'id':'1', 'name':'A'},
    {'id':'2', 'name':'B'},
    {'id':'3', 'name':'C'}
]

相同的 prod.product_id 在 3 个地方(span - id、button - id 和 a - href)被使用,但对于少数产品(5 个中有 2 个),id 是空白的。

参考下面的 HTML 截图:

不知道是什么原因,请指教。

另外,如果我错过了任何重要信息,请告诉我。

提前致谢。

【问题讨论】:

    标签: python-3.x django django-templates


    【解决方案1】:

    所以根据你的字典列表,你的键是idname所以你需要做{{ prod.id }}

    {% for prod in products %}
        <footer class="card-footer">
            <span id="atc_prod_{{ prod.id }}" class="atc_prod">prod_{{ prod.id }}
                <button class="button is-info is-small card-footer-item cart" id="prod_{{ prod.id }}">Add to Cart</button>
            </span>
            <a href="/shop/products/{{ prod.id }}"><button class="button is-small is-info card-footer-item cart" id="qv{{ prod.id }}">Quick View</button></a>
        </footer>
    {% endfor %}
    

    【讨论】:

    • 抱歉造成混淆,字典列表只是一个例子,真正的字典键名是product_id
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多