如何处理嵌套上下文

How to handle nested context?

本文关键字:嵌套 上下文 处理 何处理      更新时间:2023-09-26

我想在Mustache中使用嵌套字典,Mustache手册中的Non-False Values部分建议了这一点,并给出了以下示例:

模板:

{{#person?}}
  Hi {{name}}!
{{/person?}}

哈希:

{
   "person?": { "name": "Jon" }
}

输出:

Hi Jon!

我试着在在线演示中运行上面的例子,我得到了:

Hi !

我还尝试了pystache(pystache 0.3.1,Python 2.7.2):

import pystache
tmpl = """
{{#person}}
  Hi {{name}}!
{{/person}}
"""
dct = {
  "person": { "name": "Jon" }
}
print(pystache.render(tmpl, dct))

我得到了一个错误:

Traceback (most recent call last):
  File "test2.py", line 13, in <module>
    print(pystache.render(tmpl, dct))
  File "c:'Python27'lib'site-packages'pystache'__init__.py", line 7, in render
    return Template(template, context).render()
  File "c:'Python27'lib'site-packages'pystache'template.py", line 42, in render
    template = self.render_sections(template, context)
  File "c:'Python27'lib'site-packages'pystache'template.py", line 78, in render_sections
    insides.append(self.render(inner, item))
  File "c:'Python27'lib'site-packages'pystache'template.py", line 43, in render
    result = self.render_tags(template, context)
  File "c:'Python27'lib'site-packages'pystache'template.py", line 97, in render_tags
    replacement = func(self, tag_name, context)
  File "c:'Python27'lib'site-packages'pystache'template.py", line 105, in render_tag
    raw = context.get(tag_name, '')
AttributeError: 'str' object has no attribute 'get'

我对列表没有问题,所以下面这样的结构很好:

{
   "person?": [{ "name": "Jon" }]
}

我可以通过输入dict预处理(将字典扁平化或更改为列表)来解决问题,但为什么它不起作用?我做错什么了吗?


pystache问题的解决方案

PyPI中的pystache版本非常旧(从2010年5月开始),这就是问题所在。GitHub的版本更新了很多(嵌套字典的问题并没有出现)。

除非我们知道context在以下情况下会发生什么:

File "c:'Python27'lib'site-packages'pystache'template.py", line 43, in render
 result = self.render_tags(template, context)
File "c:'Python27'lib'site-packages'pystache'template.py", line 97, in render_tags
 replacement = func(self, tag_name, context)
File "c:'Python27'lib'site-packages'pystache'template.py", line 105, in render_tag
 raw = context.get(tag_name, '')

很难知道它为什么失败以及解决方法为什么成功,因为最终context应该是dict而不是str

我建议您将此问题提交给pystache。他们认真对待自己的问题,查看页面