问题
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