简体   繁体   English

Flask/Jinja2 继续声明

[英]Flask/Jinja2 Continue statement

Im working on a simple app, specifically the "view_cart" functionality where a user can view what items they've added to their checkout cart.我正在开发一个简单的应用程序,特别是“view_cart”功能,用户可以在其中查看他们添加到结账购物车中的项目。 I have the simple cart working, but am having trouble displaying it the way I want.我有一个简单的购物车,但无法按照我想要的方式显示它。 Specifically, for multiples of the same item, I would like there to be a quantity with a price next to that item when you view the cart, versus what i have now where each item displays individually.具体来说,对于同一商品的倍数,我希望当您查看购物车时,该商品旁边有一个数量和价格,而不是我现在每个商品单独显示的数量。 eg "beef 1, beef 1, beef 1, ham 1, ham 1. My goal is "beef 3, ham 2".例如“牛肉 1,牛肉 1,牛肉 1,火腿 1,火腿 1。我的目标是“牛肉 3,火腿 2”。

I wanted to use a for loop with Jinja but apparently break/continue(if quantity greater than 1) is not supported.我想在 Jinja 中使用 for 循环,但显然不支持 break/continue(如果数量大于 1)。 Any suggestions on how to make this work without that functionality is much appreciated.非常感谢有关如何在没有该功能的情况下完成这项工作的任何建议。 Current code below :当前代码如下:

{% include "navtemp.html" %} 

{% for i in items %}


  <div class="container">
   <div class="row">
       <div class="col-md-3">

           <img src="/static/{{ i[0][3] }}" style="width:200px;height:300px;"></div>

    <div class="col-md-3">
        <p>{{ i[0][1] }}</p>
        <p>${{ i[0][4] }}</p>
        <p>Qty: {{ items.count(i) }}</p>
        <form method="post" action="{{ url_for('pricing',cartQty=cartQty) }}">
            <input type="hidden" name="{{ i[0][1] }}" id="remove" value="remove">
            <h5><button class="btn btn-primary" type="submit">Remove</button></h5>
        </form>
    </div>

</div>

{% endfor %} {% 结束为 %}

In your view code you should group your items:在您的视图代码中,您应该对您的项目进行分组:

import itertools as it, operator as op

l = [[0,'beef','a.png',9.99],[1,'ham','b.png',7.99],[2,'beef','a.png',9.99],
     [3,'ham','b.png',7.99],[4,'beef','a.png',9.99]] 
l.sort(key=op.itemgetter(1))
items = []
for k,g in it.groupby(l,op.itemgetter(1,2,3)): 
    items.append(list(k) + [sum(1 for i in g)]) 

Then items is:然后items是:

[['beef', 'a.png', 9.99, 3], ['ham', 'b.png', 7.99, 2]]

And then you'd need to adjust your index values in your template.然后您需要调整模板中的索引值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM