为何在mako中使用Context?

0 投票
1 回答
820 浏览
提问于 2025-04-16 22:26

我看了Makotemplate的手册,里面有以下代码:

from mako.template import Template
from mako.runtime import Context
from StringIO import StringIO

mytemplate = Template("hello, ${name}!")
buf = StringIO()
ctx = Context(buf, name="jack")
mytemplate.render_context(ctx)
print buf.getvalue()

使用Context有什么好处呢?

1 个回答

1

你可能不会直接使用它,因为它包含了输出缓冲区和一个可以在模板中引用的变量字典。通常来说,使用Templaterender方法会更好。

>>> Template('hello ${name}!').render(name='jack')
<<< u'hello jack!'

你可以在这里了解更多信息。

撰写回答