Skip to main content
 首页 » 编程设计

javascript之如何处理嵌套上下文

2025年05月04日21傻小

我想在 Mustache 中使用嵌套字典,Mustache manual 中的非假值部分表明这是可能的,并提供了以下示例:

模板:

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

哈希:

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

输出:

Hi Jon! 

我试图在 online demo 中运行上面的示例我得到了:

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问题的解决

pystache 版本位于 PyPI真的很旧(从 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。他们认真对待他们的问题,看着他们的 page .