- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
这个问题是关于在子上下文中使用带有数据路径的 dust.js 模板系统。我的意图是使用键到字符串的映射来支持 i18n。
给定这样的数据:
{i18n : { firstname : "First Name" },
people : [
{"name" : "Moe"},
{"name" : "Curly"}
]}
在 dust 中,您可以使用部分来列出每个人:
{#people}
{name}
{/people}
并且您可以使用路径来访问名字 i18n 字符串:
{i18n.firstname}
但以下不起作用:
{#people}
{i18n.firstname}: {name}
{/people}
其实文档中特别说:
To avoid brittle and confusing references, paths never backtrack up the context stack. If you need to drill into a key available within the parent context, pass the key as a parameter.
所以我尝试将 key 作为参数传递:
{#people i18n=i18n}
{i18n.firstname}: {name}
{/people}
但这行不通。当我在 dust homepage 上试验这个时,我看到编译后的模板有这段代码:
"i18n": ctx.get("i18n")
这让我觉得上面的例子应该可以正常工作。
那么是什么给了?我怎样才能使它工作?
注意:以下确实有效:
{#people firstname=i18n.firstname}
{firstname}: {name}
{/people}
但如果您需要在 people 上下文中访问大量 i18n 键,这就不太适用了。
最佳答案
路径可以在键和部分中使用,以指定您希望 Dust 查找键的位置。要了解如何以及何时使用路径,您应该首先了解 Dust 在没有路径时如何查找键。你可能想坐下来。
当搜索键时,Dust 首先在当前上下文中查找,然后在每个父上下文中查找,直到没有更多的父上下文可供搜索。如果没有找到键,Dust 什么都不做(除非你使用 Exists or Not存在部分)。如果 Dust 找到了键,它将停止搜索并使用给定的值。这也不算太陌生吧?这就是 JavaScript 在执行环境中查找变量的方式。
但是,当使用路径时,Dust 不会向上看树,而是只看 child 。最好用一个例子来说明这一点。
JSON:
{
"i18n": {
"firstname": "First Name"
},
"name": "My Dust Template",
"firstname": "Surprise!",
"people": [
{
"name": {
"firstname": "Moe",
"lastname": "Howard"
}
},
{
"name": {
"firstname": "Curly",
"lastname": "Howard"
}
}
]
}
还有灰尘:
Dust Template:
{! Show the name of the template !}
{name}{~n}
{#people}
{!
As you noted, the following will not work, because
when using a path, Dust only searches
deeper into the JSON. The output will be:
": Surprise!"
!}
{i18n.firstname}: {firstname}{~n}
{!
To get your i18n string, you need to look up the
stack instead of down. This can be done by using a
section without a path, as follows. The output will be:
"First Name: Moe"
"First Name: Curly"
!}
{#i18n}{firstname}{/i18n}: {name.firstname}{~n}
{!
Note that we successfully used the path to
get the firstname of each of the people.
!}
{/people}
[编辑]:有关更多信息,请查看 Dust 的 LinkedIn 分支中的此维基页面:https://github.com/linkedin/dustjs/wiki/Where-else-does-Dust-search-if-the-value-is-not-defined%3F-A.K.A.-Dust-Scoping
关于javascript - dust.js:在作用域部分使用路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11851691/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!