使用嵌入式python和SimpleTemplate Engine作为字符串传递给template()

时间:2016-03-16 19:29:49

标签: python bottle

我正在调试一个应用程序,并希望使用SimpleTemplate瓶来呈现HTML和Python。如果我将模板用作单独的文件(views / simple.tpl),则可以正确呈现Python。

如果我尝试将Python作为字符串传递,我会得到NameError("name 'demo' is not defined",)

from bottle import template

text = "debugging"
return template(
    "<p>{{text}}</p>" + 
    "% demo = 'hello world'" + 
    "<p>{{demo}}</p>",
    text=text
)

这可能吗?

1 个答案:

答案 0 :(得分:2)

嵌入Python代码的行必须以%开头。问题是您正在使用字符串连接,这不会保留换行符。简单地说,该字符串等同于以下行:

<p>{{text}}</p>% demo = 'hello world'<p>{{demo}}</p>

由于%不是第一个字符,因此它并不意味着要装瓶。

手动添加换行符:

return template(
    "<p>{{text}}</p>\n"
    "% demo = 'hello world'\n" 
    "<p>{{demo}}</p>",
    text=text
)

作为旁注,您可以使用implicit string literal concatenation(如上面的代码所示)。