【问题标题】:How to reference multi-word dictionary key in mako?如何在mako中引用多词词典键?
【发布时间】:2012-11-03 02:25:02
【问题描述】:

我通过csv.DictReader 将一个 csv 文件传递​​给 Mako,并且字典使用行标题作为键。其中一些具有诸如“条目 ID”之类的名称。当我尝试在模板中引用这些多字键时,Mako 会抛出错误。具体来说,错误信息是mako.exceptions.SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1)

以下代码演示了我遇到的问题:

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)

有没有办法为多字键转义空格?

【问题讨论】:

    标签: python mako


    【解决方案1】:

    我找到了一种可行的方法,但如果可能的话,我宁愿将字典作为 **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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多