如何处理嵌套上下文
How to handle nested context?
我想在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。他们认真对待自己的问题,查看页面。
相关文章:
- 用嵌套函数和默认函数定义函数
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 可以简化嵌套的延迟Q Promises解析吗
- 用于搜索的聚合物嵌套绑定
- 如何使用javascript获取嵌套对象中所有子对象的单个属性
- d3中堆栈函数和嵌套函数之间的差异
- 如何打印嵌套对象的所有值
- JavaScript 中的嵌套函数和 “this” 关键字
- 设置嵌套对象属性的更好方法
- querySelector/getElementByClassName嵌套项的顺序
- 猫鼬在特定记录中查找嵌套记录
- 访问嵌套JSON对象的键,其中键是动态的
- 画布是否支持嵌套的上下文保存
- JavaScript承诺:具有绑定的深度嵌套上下文(this)
- 如何处理嵌套上下文
- 在挖空视图中访问$parent的$parent - 嵌套上下文
- 嵌套在回调中的JSONParse数组丢失了上下文
- 嵌套setInterval函数,成功更改多个画布动画的画布上下文
- 嵌套执行上下文的生存期
- 嵌套函数中的函数上下文(“this”)