在Python模板语言Mako中,如何使用只有在运行时才知道的名称调用template def?

2024-05-23 18:00:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种调用def模板的方法,该模板由上下文中可用的数据决定。在

编辑:同一问题的简单实例。在

可以在上下文中发出对象的值:

# in python
ctx = Context(buffer, website='stackoverflow.com')

# in mako
<%def name="body()">
I visit ${website} all the time.
</%def>

产生:

^{pr2}$

我想允许根据数据定制输出。在

# in python 
ctx = Context(buffer, website='stackoverflow.com', format='text')

# in mako
<%def name="body()">
I visit ${(format + '_link')(website)} all the time. <-- Made up syntax.
</%def>

<%def name='html_link(w)'>
<a href='http://${w}'>${w}</a>
</%def>

<%def name='text_link(w)'>
${w}
</%def>

在上下文中更改format属性应该会更改

I visit stackoverflow.com all the time.

I visit <a href='http://stackoverflow.com'>stackoverflow.com</a> all the time.

我在bodydef中使用的合成语法显然是错误的。我需要什么来动态地指定一个模板,然后调用它?在


Tags: the数据nameincom模板formattime
2条回答

使用mako的local名称空间,但下面是一个有效的示例:

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

mytemplate = Template("""
<%def name='html_link(w)'>
<a href='http://${w}'>${w}</a>
</%def>
<%def name='text_link(w)'>
${w}
</%def>
<%def name="body()">
I visit ${getattr(local, format + '_link')(website)} all the time.
</%def>
""")

buf = StringIO()
ctx = Context(buf, website='stackoverflow.com', format='html')
mytemplate.render_context(ctx)
print buf.getvalue()

根据需要,这会发出:

^{pr2}$

如果您首先(从另一个模板:)生成模板,然后用您的数据运行该模板如何?在

相关问题 更多 >