2011-11-18 75 views
2

元组我一直在使用bottlepy和我有这样一件事:如何呈现bottlepy

..code.. 
comments = [(u'34782439', 78438845, 6, u'hello im nick'), 
(u'34754554', 7843545, 5, u'hello im john'), 
(u'332432434', 785345545, 3, u'hello im phil')] 

return comments 

在视图我已经做到了这一点:

%for address date user text in comments: 
     <h3>{{address}}</h3> 
     <h3>{{date}}</h3> 
     <h3>{{user}}</h3> 
     <h3>{{text}}</h3> 
%end 

当我启动服务器,错误是:

Error 500: Internal Server Error 

Sorry, the requested URL http://localhost:8080/hello caused an error: 

Unsupported response type: <type 'tuple'> 

我怎么能把它渲染到视图中?

(对不起,我的英语)

回答

7

您的代码有两个问题。首先,响应不能是元组列表。正如Peter所说,它可以是字符串或字符串列表,或者,如果您想使用视图,它可以(也应该)成为视图变量的字典。键是变量名称(这些名称,如comments,将在视图中可用),值是任意对象。

所以,你的处理函数可以改写为:

@route('/') 
@view('index') 
def index(): 
    # code 
    comments = [ 
     (u'34782439', 78438845, 6, u'hello im nick'), 
     (u'34754554', 7843545, 5, u'hello im john'), 
     (u'332432434', 785345545, 3, u'hello im phil')] 
    return { "comments": comments } 

通知的@view@route装饰。

现在,您的视图代码有问题:元组解包中的逗号缺失。因此,您的视图(命名在我的情况index.html)应该是这样的:

%for address, date, user, text in comments: 
    <h3>{{address}}</h3> 
    <h3>{{date}}</h3> 
    <h3>{{user}}</h3> 
    <h3>{{text}}</h3> 
%end 
+0

我有查看和路由装饰器,“..代码..”是他们的缩写..我的错误是“返回评论”和逗号。谢谢你的帮助!我是python新手,但还不清楚。 – Nicky

4

我相信瓶期待一个字符串或字符串列表,所以你可能需要将其转换和解析。

return str(result) 

对于格式化结果的方式,看看一节“瓶模板格式化输出”在http://bottlepy.org/docs/dev/tutorial_app.html

+0

谢谢你,我已经失去了联系! – Nicky

+0

没问题,不要忘记提高你认为有用的答案! –

+0

非常感谢。 :) –