Skip to main content
 首页 » 编程设计

python之Pylons 分页器问题

2025年05月04日13telwanggs

Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator.

来自 http://pylonsbook.com/en/1.1/simplesite-tutorial-part-2.html

我无法让它工作,分页器不会将东西传递给 h.url_for,我遵循了教程。我必须将 pageid 添加到 list.html 中的 h.url_for。我该如何解决?

部分代码:

        ${h.link_to( 
            comment.id, 
            h.url_for( 
                controller=u'comment', 
                action='view', 
                id=unicode(comment.id) 
            ) 
        )} 

但在我输入之前它无法正常工作

        ${h.link_to( 
            comment.id, 
            h.url_for( 
                controller=u'comment', 
                action='view', 
                id=unicode(comment.id), 
                pageid = c.page.id 
            ) 
        )} 

编辑:问题是在教程中它说分页器将通过这段代码:

    c.paginator = paginate.Page( 
        comments_q, 
        page=int(request.params.get('page', 1)), 
        items_per_page=10, 
        pageid=c.page.id, 
        controller='comment', 
        action='list' 
        ) 
    return render('/derived/comment/list.html') 

但除非我手动输入,否则它不会发生

请您参考如下方法:

您需要将 pageid 传递给 url_for 方法,因为路由需要 pageid。

map.connect('/page/{pageid}/{controller}/{action}', requirements={'pageid':'\d+'}) 
map.connect('/page/{pageid}/{controller}/{action}/{id}', requirements={'pageid':'\d+', 'id':'\d+'}) 

pageid 然后在您的评论 Controller 中以 before 方法进行处理

def __before__(self, action, pageid=None): 
    page_q = meta.Session.query(model.Page) 
    c.page = pageid and page_q.filter_by(id=int(pageid)).first() or None 
    if c.page is None: 
        abort(404) 

然后,c.page 设置为当前页面,评论可以链接到这个c.page。