どのように私はPythonのテンプレート言語真子に、実行時に知られている名前のテンプレートDEFSを呼ぶのですか?

StackOverflow https://stackoverflow.com/questions/923837

  •  06-09-2019
  •  | 
  •  

質問

私は、コンテキストで利用可能なデータによって決定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.

を作っ構文の私はbodydefで使用している、明らかに間違っています。私はそれを呼び出して何を動的にテンプレートを指定する必要があり、でしょうか?

役に立ちましたか?

解決

マコさん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.

他のヒント

どのようにあなたが最初に別のテンプレート:)から(テンプレートを生成して、あなたのデータとそれを実行した場合はどうですか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top