如何在 Python 模板语言 Mako 中调用仅在运行时已知的名称的模板定义?
我正在尝试找到一种调用由上下文中可用数据确定的 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组成语法 code> 显然是错误的。 我需要什么来动态指定模板,然后调用它?
I am trying to find a way of calling def templates determined by the data available in the context.
Edit: A simpler instance of the same question.
It is possible to emit the value of an object in the context:
# in python
ctx = Context(buffer, website='stackoverflow.com')
# in mako
<%def name="body()">
I visit ${website} all the time.
</%def>
Produces:
I visit stackoverflow.com all the time.
I would like to allow a customization of the output, based upon the data.
# 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>
Changing the format
attribute in the context should change the output from
I visit stackoverflow.com all the time.
to
I visit <a href='http://stackoverflow.com'>stackoverflow.com</a> all the time.
The made up syntax I have used in the body
def
is obviously wrong. What would I need to dynamically specify a template, and then call it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要对 mako 的
local
命名空间进行一些操作,但这里有一个工作示例:根据需要,它会发出:
Takes some playing with mako's
local
namespace, but here's a working example:As desired, this emits:
如果您首先生成模板(从另一个模板:),然后使用您的数据运行它怎么样?
How about if you first generate the template (from another template :), and then run that with your data?