【问题标题】:Jinja2 ValueError: too many values to unpack (expected 2)Jinja2 ValueError:解包的值太多(预期为 2)
【发布时间】:2022-01-02 00:39:42
【问题描述】:
{%for feed,tim in feeds,time %}
                        {% set nickname = feed.nick %}
                        {% set like = feed.like %}
                        {% set text = feed.text %}
                        {% set today = tim %}
                        {% set postid = feed.postid %}
                        {% set photo = feed.photo %}
                        {% set profile = feed.profile %}
                        
                        

                                {%for cmt in cmts %}
                                {% set nickname = cmt.nick %}
                                {% set cmt = cmt.cmt %}
                                {% set cmtid = cmt.cmtid %}
                                {% if cmtid == postid %}
                                <p class="description"><span>{{nickname}} </span> {{cmt}}</p>
                                {% endif %}
                                {% endfor %}

                                <div class="comment-wrapper">
                                    <img src="../static/images/smile.PNG" class="icon" alt="">
                                    <input type="text" class="comment-box" id='cmt' placeholder="Add a comment">
                                    <button class="comment-btn" onclick=cmt_write()>post</button>
                                </div>
                            </div>


                        </div>
                        {% endfor %}

在jinja2中用一个列表成功执行for语句, 但我们必须使用两个列表。

我尝试在 jinja2 中使用 2 个列表(提要、时间)

如何从 jinja2 循环 jinja2

有没有办法在 jinja2 中使用两个列表?

【问题讨论】:

  • 在视图函数中告诉我们feedstime的定义。

标签: python jinja2


【解决方案1】:

如果您想遍历两个列表(长度相同)的组合列表,您必须对它们应用 zip 函数。例如:

def view_function():
   feeds = [...]
   time = [...]
   
   feeds_and_time = zip(feeds, time)
   # Looks like this: [('feed_1', 'time_1'), ('feed_2', 'time_2')]

然后将这个新的feeds_and_time 变量传递给渲染函数。并在模板中,修改循环:

{% for feed,tim in feeds_and_time %}

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 2014-07-31
    • 2017-12-14
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多