如何在Jinja2中使用简单的for循环构建HTML表? [英] How to build up a HTML table with a simple for loop in Jinja2?

查看:65
本文介绍了如何在Jinja2中使用简单的for循环构建HTML表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Jinja2.我之前从未做过任何模板工作,因此现在我发现文档非常混乱.

I'm just learning Jinja2. I have never done any templating before so I find the documentation very confusing right now.

如何使用简单的FOR循环构建HTML表?我的模板如下所示:

How do I do build up a HTML table with a simple FOR loop? My template looks something like this:

{% for item in items %}
<TR>
   <TD class="c1"><IMG src="favicon.ico"></TD>
   <TD class="c2">{{date}}</TD>
   <TD class="c3">{{id}}</TD>
   <TD class="c4"><SPAN>{{position}}</SPAN></TD>
   <TD class="c5"><SPAN>{{status}}</SPAN></TD>
</TR>
{% endfor %}

我的python代码如下:

My python code looks like this:

import jinja2
loader = jinja2.FileSystemLoader('./index.html')
env = jinja2.Environment(loader=loader)
template = env.get_template('')
print template.render(date='2012-02-8', id='123', position='here', status='Waiting')

我似乎无法生成任何表.我也不知道这是否是填充具有多个字段的表的最佳方法.

I can't seem to generate any tables. I also don't know if this is the best way to populate a table with several fields.

推荐答案

只需将items传递给template.render作为关键字参数-它应该是项目的列表(实际上是所有可迭代的对象).如果需要子项目,请使用类或字典.在最简单的情况下,您可以使用字典:

Just pass items to template.render as a keyword argument - it should be a list (really any iterable will do) of items. If you need sub-items use a class or a dictionary. In the simplest case, you can use a dictionary:

items = []
for i in range(1, 11):
    i = str(i)

    # dict == {}
    # you just don't have to quote the keys
    an_item = dict(date="2012-02-" + i, id=i, position="here", status="waiting")
    items.append(an_item)

# ... your code here ...

template.render(items=items)

然后您的Jinja代码将略有变化:

And then your Jinja code would change slightly:

<table>
{% for item in items %}
<TR>
   <TD class="c1"><IMG src="favicon.ico"></TD>
   <TD class="c2">{{item.date}}</TD>
   <TD class="c3">{{item.id}}</TD>
   <TD class="c4"><SPAN>{{item.position}}</SPAN></TD>
   <TD class="c5"><SPAN>{{item.status}}</SPAN></TD>
</TR>
{% endfor %}
</table>

这篇关于如何在Jinja2中使用简单的for循环构建HTML表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆