在Bottle中向模板传递列表

2 投票
1 回答
5623 浏览
提问于 2025-04-17 17:25

我有一个包含帖子信息的列表,这个列表是由多个元组组成的(就是一个元组的列表)。但是我遇到了一个问题,就是怎么把这个列表传递给Bottle框架的模板。我试了很多方法,也查看了StackOverflow上大部分的问题,但就是找不到一个好的、清晰的解决方案。

这是我尝试过的:

@route('/v/:name')
def page_viwer(name):
    id=db.searchU('user', name)
    result=db.searchU_forG(id[0][0])
    if len(result)>0:#if we got posts 
        return template('v',post=result)

还有这里是 v.tpl

<html>
%for post in res:
    %for id, title, dec, pic,not_needed in post:
        <h3>{{id}}</h3>
        <h3>{{title}}</h3>
        <h3>{{dec}}</h3>
        <h3>{{pic}}</h3>
        <br/>
%end
</html>

当我尝试这个的时候,出现了500错误……我查看了日志,发现原因是:

%for id, title, dec, pic in post: TypeError: 'int' object is not iterable

1 个回答

7

我查了一下,发现这个方法很好用,效果也不错……

<html>

<table>
  %for item in res:
    title:{{item[1]}}
    <br/>
    Decription:{{item[2]}}
    <br/>
    Picture:{{item[3]}}
    <br/>
    posted by:{{item[4]}}
    <br/>
    <br/>
  %end
</table>

</html>

撰写回答