2011-12-19 55 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