Python Template Language Mako에서 런타임에만 알려진 이름으로 템플릿 DEF를 호출하려면 어떻게해야합니까?
문제
상황에서 사용 가능한 데이터에 의해 결정된 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
분명히 잘못되었습니다. 템플릿을 동적으로 지정 한 다음 호출하려면 무엇이 필요합니까?
해결책
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.
다른 팁
먼저 템플릿을 생성 한 다음 (다른 템플릿에서 :)에서 데이터를 사용하여 실행하는 경우 어떻습니까?
제휴하지 않습니다 StackOverflow