Genshi for循环不工作......?

时间:2014-09-24 18:29:45

标签: python genshi

我在使用Genshi py:for属性时遇到问题。我做错了什么?代码写在下面;要运行,使用Python 2创建virtualenv,执行pip install genshi flask,复制隔离目录中列出的文件,然后运行python hello.py

代码

hello.py的内容:

import os.path
import traceback

import flask
import genshi.template


app = flask.Flask(__name__)
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
loader = genshi.template.TemplateLoader(template_dir, auto_reload=True)


MESSAGES = [
    "Hello",
    "World",
    "Sup?",
]


@app.route("/", defaults={"name": ""})
@app.route("/<path:name>")
def show(name):
    template_name = name + ".html"
    try:
        template = loader.load(template_name)
        stream = template.generate(
            messages=MESSAGES,
        )
        rendered = stream.render('html', doctype='html')
    except Exception as e:
        tb = traceback.format_exc()
        return "Cannot load /{}: {} <pre>\n{}</pre>".format(name, e, tb)

    return rendered


if __name__ == '__main__':
    app.run()

templates/debug.html的内容:

<!DOCTYPE html>
<html
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:py="http://geshi.edgewall.org/"
    >
  <body>
    <p>Messages is a ${str(type(messages))} of length ${len(messages)}</p>

    <p>Messages:</p>
    <pre>
${'\n'.join(m + "!" for m in messages)}
    </pre>
  </body>
</html>

templates/hello.html的内容:

<!DOCTYPE html>
<html
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:py="http://geshi.edgewall.org/"
    >
  <body>
    <h1>Messages</h1>

    <ul>
        <li py:for="msg in messages">
            $msg
        </li>
    </ul>
  </body>
</html>

问题

当我访问http://localhost:5000/debug时,一切似乎都按预期工作,但当我运行http://localhost:5000/hello时,我得到了#34;无法渲染/你好:&#39; msg&#39;未定义&#34;

1 个答案:

答案 0 :(得分:3)

您在命名空间定义中缺少'n'。它目前正在读取 'xmlns:py =“http://geshi.edgewall.org/”'但它应该是'xmlns:py =“http://genshi.edgewall.org/”'。这导致Genshi无法识别'py:for'属性,然后愉快地尝试评估'$ msg'而没有任何'for msg in messages'来定义变量。