簡體   English   中英

如何從 Flask/jinja2 循環中的列表中刪除元素?

[英]How do I remove elements from a list in a Flask/jinja2 loop?

我目前正在制作一個flask項目,我想在其中每行顯示四個Bootstrap列。為了做到這一點,我想我可以這樣做:

my_list = ["a","b","c","d","e","f","g","h","i","k",
       "l","m","n","o","p","q","r","s","t","u",
       "v","w","x","y","z"]

for i in range(len(my_list)):
    for i in my_list[:4]:
        print(i)
        my_list.remove(i)

# returns every element of my_list in order

但是,當我嘗試在實際項目中執行此操作時,無論我放在哪里,都會出現錯誤

{% number_of_texts.remove[j] %}: "jinja2.exceptions.TemplateSyntaxError: 遇到未知標簽 'number_of_texts'。Jinja 正在尋找以下標簽:'endfor' 或 'else'。需要關閉的最里面的塊是'為了'。”

這些是我在 main.py 中的變量:

@app.route('/texts')
def texts():
number_of_texts = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
return render_template('texts.html', title="All texts", number_of_texts=number_of_texts, len=len(number_of_texts))

這是我來自 texts.py 的代碼:

{% for i in range(len) %}
<div class="row"> 
    {% for j in number_of_texts[:4] %}
        <div class="col m-1"> 
            <div class="card" style="width: 15rem; height: 28rem; border-radius: 25px 25px 0px 0px">
                <img src="static\img\p_01.jpg" class="card-img-top" alt="..." style="object-fit: cover; border-radius: 25px 25px 0px 0px">
                <div class="card-body">
                    <h5 class="card-title">row: {{ i }}</h5>
                    <p class="card-text">column: {{ j }}</p>
                    <a href="{{ url_for('specific_text', text_no=1) }}" class="btn btn-dark">Button</a>
                </div>
            </div>
        </div>
    {% endfor %}{% number_of_texts.remove[j] %}
</div>
{% endfor %}

如果我不從列表number_of_texts刪除j ,那么當然除了獲得太多列之外,我還得到了我真正想要的布局。 這是它的樣子: https : //imgur.com/a/t6tIic4

有沒有另一種方法可以從list刪除這些項目,以便我只顯示列表中的每個元素一次?

此致

如果您的實際用例是將事物分成幾行,則您只需要batch過濾器

{% for row in things|batch(4) %}
  <div class="row">
     {% for item in row if item %}
        <div class="item">
           {{ item }}
        </div>
     {% endfor %}
  </div>
{% endfor %}

請參閱有關fill_with=參數的上述文檔; 由於if itemif item things的長度不能被 4 整除,則上述內容只會使最后一行具有較少的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM