How to reference multi-word dictionary key in mako?

可紊 提交于 2019-12-13 20:26:36

问题


I am passing a csv file to Mako via csv.DictReader, and the dictionary uses row headers for keys. Some of these have names like 'Entry Id'. Mako throws out errors when I try to reference these multi-word keys in a template. Specifically, the error message is mako.exceptions.SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1).

The following code demonstrates the issue I am experiencing:

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)

Is there a way to escape spaces for multi-word keys?


回答1:


I have found one way that works, but I'd rather send the dictionary as **kwargs if possible. Here is the working solution:

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)


来源:https://stackoverflow.com/questions/13381391/how-to-reference-multi-word-dictionary-key-in-mako

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!