我怎么叫,只有在运行时在Python模板语言Mako的知名的品牌模板DEFS?
题
我想找到调用由上下文提供的数据确定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
使用显然是错误的。什么会我需要动态指定模板,然后把它?
解决方案
需要一些上场与灰鲭鲨的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.
其他提示
怎么样,如果你第一次生成模板(从另一个模板:),然后用你的数据运行?
不隶属于 StackOverflow