Pylons:如何编写自定义404页面?

2 投票
2 回答
707 浏览
提问于 2025-04-16 08:34

这个问题之前有人问过,但没有详细回答。

我想要替换掉默认的Pylons错误页面,做一个更好看的自定义页面。我已经在error.py里覆盖了控制器,代码如下:

def document(self):
    """Render the error document"""
    resp = request.environ.get('pylons.original_response')
    content = literal(resp.body) or cgi.escape(request.GET.get('message', ''))
    custom_error_template = literal("""\
    # some brief HTML here
    """)
    page = custom_error_template % \
        dict(prefix=request.environ.get('SCRIPT_NAME', ''),
             code=cgi.escape(request.GET.get('code', str(resp.status_int))),
             message=content)
    return page

这样做是可以的。接下来我想在模板目录中使用一个模板,这样404页面就可以继承我平常用的布局模板、CSS等。

(我知道对于500错误这样做不好——我会在error.py里检查代码是否是404,然后再使用模板,而不是直接用文字。)

所以,我的问题是:我该如何定义custom_error_template,让它指向我的模板,而不是直接用文字呢?

2 个回答

0

只需要创建你的视图,然后使用 add_notfound_view 这个配置方法来进行设置。

查看详情: http://docs.pylonsproject.org/docs/pyramid/en/latest/api/config.html?highlight=document%20error#pyramid.config.Configurator.add_notfound_view

1

你可以使用 render 方法(从 yourapp.lib.base 导入它),然后用 return render('/path/to/error/template') 来返回错误模板。

撰写回答