gpt4 book ai didi

javascript - dust.js:在作用域部分使用路径

转载 作者:搜寻专家 更新时间:2023-11-01 05:13:52 24 4
gpt4 key购买 nike

这个问题是关于在子上下文中使用带有数据路径的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com