【问题标题】:How do I iterate zip list in jinja2 using for loop and display values in HTML table?如何使用 for 循环在 jinja2 中迭代 zip 列表并在 HTML 表中显示值?
【发布时间】:2017-09-12 12:46:33
【问题描述】:

我试图在 jinja2 中迭代 zip 列表并在 HTML 表中显示值,但每次尝试使用空白页都失败了,但是,我可以在无序列表中显示值,如下所示。

<ul>
      {% for bus, info in jnjbus_info %}
       <li>{{bus}}</li>
       <li>{{info}}</li>
{% endfor %}
</ul>

这是我将值传递给模板的烧瓶/函数:

@app.route('/busses')
def busses():
    bus_type = ['AC', 'NON-AC', 'Sleeper', 'NON-Sleeper']   
    bus_info = ['1010', '2020', '3030', '4040']   
    return render_template('busses.html', jnjbus_info=zip(bus_type, bus_info))

我正在渲染名为 busses.html 的模板 这是脚本:

    <table style="width:100%">
        <tr>
            <th>Bus Type</th>
            <th>Bus Information</th>
        </tr>
            {% for bus, info  in jnjbus_info %}
                <tr>    
                <td>{{bus}}</td>
                <td>{{info}}</td>               
               </tr>
           {% endfor %} 
    </table>

【问题讨论】:

  • 围绕trs 移动循环?您想生成 N 多行两列 - 不是一行有大量列彼此相邻,对吧?另外 - 你应该在那里放一个thead和tbody......
  • 我也试过了,没有成功。
  • edit您的问题以显示最新代码 - 您是否还在浏览器中查看了您的页面源代码,以查看是否有任何看起来像是试图输出但只是没有导致它的东西由样式表等显示...?
  • 好的,我将编辑问题,我也查看了源代码,没有任何内容,无论我放在循环中的任何 HTML 标记都不会显示在页面源代码中。

标签: python-3.x flask jinja2


【解决方案1】:

你没有

<tbody> </tbody> 

我在您的页面中添加了标签并且它有效:

<table style="width:100%">
    <tr>
        <th>Bus Type</th>
        <th>Bus Information</th>
    </tr>
     <tbody>
    {% for bus, info  in jnjbus_info %}
        <tr>


            <td>{{bus}}</td>
            <td>{{info}}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

这是它的样子:

【讨论】:

  • 那我这边怎么了? here's the screen shot of page source
  • 我按照你的建议添加了&lt;tbody&gt;&lt;/tbody&gt;,请看之前评论中的屏幕截图,我会从头开始尝试,知道发生了什么问题。
  • 你的代码看起来也不错,看起来是问题查看浏览器:尝试做一个空缓存
  • 请用提供图片输出的完整 html 更新您的问题?
  • 我不知道出了什么问题,我编写了类似的脚本并在port=8888 上运行,它就像魅力一样。由于一个愚蠢的端口原因,这个错误浪费了我将近 6 个小时。这是干净的工作代码pyhtml screen shot
【解决方案2】:

这个问题提供的代码是没有bug的,但是port=5000引起的问题,也可能是浏览器cache引起的。在解决该错误时,我编写了一个类似的脚本 pyhtmlscreen shot 。并在 port=8888 上运行,这就像魅力一样。 注意: 考虑在不同的ports 上运行相同的应用程序并清除浏览器cache

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2020-07-02
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2020-02-26
    • 2019-11-15
    • 2022-07-11
    • 2017-09-22
    相关资源
    最近更新 更多