如何处理嵌套上下文?
我想在Mustache中使用嵌套字典,Mustache手册中的非假值部分提到这是可能的,并给出了以下示例:
模板:
{{#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" }]
}
我可以通过预处理输入字典(扁平化或将字典转换为列表)来找到解决办法,但为什么它不工作呢?我是不是做错了什么?
pystache问题的解决方案
在PyPI上找到的pystache版本非常旧(是2010年5月的),这就是问题所在。而在GitHub上的版本要新得多(而且嵌套字典的问题不会出现)。
1 个回答
0
除非我们知道在以下情况下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。他们非常重视问题,可以在他们的页面上查看。