Pylons 中“全局名称 'c' 未定义”

1 投票
1 回答
3848 浏览
提问于 2025-04-15 17:54

我设置了Pylons v0.9.7,并用genshi创建了一个项目。然后我尝试写一个简单的测试案例,但它没有正常工作。

代码:member.py

coding: utf-8 
import logging import foo.model

from foo.lib.base import *

log = logging.getLogger(__name__)

class MemberController(BaseController):

    def index(self):
        c.title="title"
        c.mes="message"
        return render('test.html')

代码:test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:py="http://genshi.edgewall.org/"
      lang="ja">
    <head>
        <title>${c.title}</title>
    </head>
<body>
    <p>${c.mes}</p>
</body>
</html>

还有错误信息(在日志中)

Error - <type 'exceptions.NameError'>: global name 'c' is not defined

请帮我找出错误。

1 个回答

2
    c.title="title"

需要定义一个名字为 c 的东西(可以是全局的也可以是局部的)。你从来没有定义过任何c 的东西。

所以,在你给 c.title 赋值之前,先定义一个合适的名字 c(确保可以设置属性 title 的那种)!

下一个提示:from pylons import tmpl_context as c -- 你没有做过 from ... import ... as 这种写法,对吧?-)

撰写回答