2012-11-14 19 views
0

我通過csv.DictReader將csv文件傳遞給Mako,並且該字典使用鍵標題。其中一些名稱如「Entry Id」。當我嘗試在模板中引用這些多字鍵時,Mako拋出錯誤。具體而言,錯誤消息是mako.exceptions.SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1)如何引用mako中的多字詞典鍵?

下面的代碼演示問題我遇到:

from mako.template import Template 

mydata = {'foo': 'bar', 'better foo': 'beach bar'} 
working_template = Template("Let's go to the ${foo}") 
fail_template = Template("Let's go to the ${better foo}") 

# this works 
print working_template.render(**mydata) 
# this generates an Exception 
print fail_template.render(**mydata) 

有沒有辦法逃避多字鍵的空間?

回答

0

我發現了一種可行的方法,但我寧願將字典作爲** kwargs發送(如果可能)。這裏是工作解決方案:

from mako.template import Template 

mydata = {'foo': 'bar', 'better foo': 'beach bar'} 
working_template = Template("Let's go to the ${foo}") 
fail_template = Template("Let's go to the ${mydata['better foo']}") 

print working_template.render(**mydata) 
print fail_template.render(mydata=mydata)