[英]Python templates and function execution
我有一个问题,基本上是关于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)的函数进行替换,然后将返回值替换为模板。
实际上很容易:)
只需模仿dict的工作原理,就可以完成。
class Scope(object):
def __getitem__(self, key):
return 'call for %s' % key
print final.substitute(Scope())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.