2011-12-19 57 views
1

我有一個問題,這基本上是一個關於Python模板引擎功能的問題。Python模板和函數執行

假設我有以下代碼:

import string as st 

def foo(bar): 
    if bar: 
     t = 'world' 
    else: 
     t = 'not happening' 

    return t 

temp = st.Template("hello $bar") 
final = temp.some_substitute_magic() 

然後

print final 

應該給

hello world 

是否有可能做到這一點與一些Python的魔力?

我知道如何做一個safe_substitute與字典,但我想知道如何做一個函數的替代與每個標識符(在這種情況下$ bar)傳遞,然後返回值被代入模板。

回答

0

其實很容易:)

只是模擬字典的工作,你就完成了。

class Scope(object): 
    def __getitem__(self, key): 
     return 'call for %s' % key 

print final.substitute(Scope()) 
+0

謝謝,它完成了這項工作!它也讓我多瞭解了一些類,這讓我意識到Python是一種非常整齊有力的編程語言。謝謝! – 2011-12-19 14:26:58