2013-06-03 47 views
1

我有以下腳本:pystache可以告訴我一個模式沒有被定義嗎?

import pystache 
d = { 
    'MSG' : 'bye' 
} 
print pystache.render('I say {{MSG}} {{THIS_IS_UNDEFINED}}', d) 

它打印:

I say bye 

但其實我是想pystache因爲有一個未定義的模式引發異常。在我的真實代碼中,事情更復雜,因此獲取關於哪些模式未定義的提示將非常有價值。

是否可以爲它配置pystache?

回答

4

使用Renderermissing_tags="strict"

>>> import pystache 
>>> pystache.Renderer(missing_tags="strict").render("I say {{MSG}} {{THIS_IS_UNDEFINED}}", d) 
KeyNotFoundError: Key u'THIS_IS_UNDEFINED' not found: first part 

你可以定義自己的功能strictrender

def strictrender(s, d): 
    renderer = pystache.Renderer(missing_tags='strict') 
    return renderer.render(s, d) 
0

我不知道pystache。我可以提出一個幫手,而不是 - 使用format()

def render(fmt, d): 
    fmt.replace('{{', '{').replace('}}', '}').format(**d) 
    return pystache.render(fmt, d) 

,也許你可以做pystache.render = render

當然,這不是一個完美的解決方案。

+0

謝謝,但沒有。 Pystache(python中的鬍子實現)比這個功能更豐富。我的例子故意非常簡單。 – dangonfast

相關問題