0

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

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

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

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

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

产生:

I visit stackoverflow.com all the time. 

我想允许根据数据自定义输出。

# 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.

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

4

2 回答 2

1

玩弄 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()

根据需要,这会发出:

I visit 
<a href='http://stackoverflow.com'>stackoverflow.com</a>
 all the time.
于 2009-05-30T19:33:33.737 回答
0

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

于 2009-05-29T01:48:31.677 回答