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 に答える