我可以将 Mustache 限制在当前范围内吗?
Can I limit Mustache to the current scope?
在Mustache中有没有办法只引用当前范围?
{
"name": "name1",
"list": [
{
"name": "name2",
"value": 200
},
{
"value": 300
}
]
}
输出:
- 名称 2: 200
- name1: 300
因为它搜索祖先范围。
但是我需要的是:
- 姓名 2: 200
- 300
有没有办法避免这样的命名空间冲突?
我不想在名称应该为空的对象中设置 "name": ""
,因为它是动态创建的。
目前无法在符合规范的 Mustache 中实现您想要的功能。但是,这并不意味着不可能:)
几种方法:
有 a proposed spec extension — 有时称为 "anchored dot notation" — 可以让您编写 {{ .name }}
……它基本上是隐式迭代器 {{ . }}
的组合,它指的是当前部分上下文和点符号,{{ foo.name }}
。请注意,它尚未添加到许多 Mustache 实现中,因此这可能不适合您,具体取决于您的口味。
如果您的 Mustache 库实现了 the proposed filters specs, you might be able to use that to prevent checking parent section contexts. The viability of this answer depends a lot on your language. In Ruby you can do it with a proxy that implements #method_missing
. In PHP, you can do the same with __isset
and __get
... Here's an example of that in PHP.
中的任何一个
但实际上,最简单的答案是始终在您的子对象中指定一个 name
属性。如果有一个 name
并且它是一个空字符串,则甚至不会检查父上下文。
在Mustache中有没有办法只引用当前范围?
{
"name": "name1",
"list": [
{
"name": "name2",
"value": 200
},
{
"value": 300
}
]
}
输出:
- 名称 2: 200
- name1: 300
因为它搜索祖先范围。
但是我需要的是:
- 姓名 2: 200
- 300
有没有办法避免这样的命名空间冲突?
我不想在名称应该为空的对象中设置 "name": ""
,因为它是动态创建的。
目前无法在符合规范的 Mustache 中实现您想要的功能。但是,这并不意味着不可能:)
几种方法:
有 a proposed spec extension — 有时称为 "anchored dot notation" — 可以让您编写
{{ .name }}
……它基本上是隐式迭代器{{ . }}
的组合,它指的是当前部分上下文和点符号,{{ foo.name }}
。请注意,它尚未添加到许多 Mustache 实现中,因此这可能不适合您,具体取决于您的口味。如果您的 Mustache 库实现了 the proposed filters specs, you might be able to use that to prevent checking parent section contexts. The viability of this answer depends a lot on your language. In Ruby you can do it with a proxy that implements
#method_missing
. In PHP, you can do the same with__isset
and__get
... Here's an example of that in PHP. 中的任何一个
但实际上,最简单的答案是始终在您的子对象中指定一个
name
属性。如果有一个name
并且它是一个空字符串,则甚至不会检查父上下文。