dust.js:在作用域中使用路径

JBC*_*BCP 4 javascript internationalization dust.js

这个问题是关于使用dust.js模板系统和子上下文中的数据路径.我的意图是使用键到字符串的映射来支持i18n.

给出这样的数据:

{i18n : { firstname : "First Name" },
 people : [
    {"name" : "Moe"},
    {"name" : "Curly"}
 ]}
Run Code Online (Sandbox Code Playgroud)

在灰尘中,您可以使用部分列出每个人:

{#people}
    {name}
{/people}
Run Code Online (Sandbox Code Playgroud)

并且您可以使用路径来访问firstname i18n字符串:

{i18n.firstname}
Run Code Online (Sandbox Code Playgroud)

但以下不起作用:

{#people}
    {i18n.firstname}: {name}
{/people}
Run Code Online (Sandbox Code Playgroud)

事实上,文档特别说:

为了避免脆弱和混乱的引用,路径永远不会回溯上下文堆栈.如果需要钻取父上下文中的可用键,请将该键作为参数传递.

所以我尝试将密钥作为参数传递:

{#people i18n=i18n}
    {i18n.firstname}: {name}
{/people}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.当我在尘埃主页上试验这个时,我看到编译的模板有这个代码:

"i18n": ctx.get("i18n")
Run Code Online (Sandbox Code Playgroud)

这让我觉得上面的例子应该可以正常工作.

什么给出了什么?我怎样才能做到这一点?

注意:下面工作:

{#people firstname=i18n.firstname}
    {firstname}: {name}
{/people}
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要在人员环境中访问大量i18n密钥,这种方法效果不佳.

smf*_*ote 5

可以在键和部分中使用路径来指定您希望Dust查找键的位置.要了解如何以及何时使用路径,您应该首先了解Dust在没有路径时如何查找密钥.你可能想坐下来.

在搜索键时,Dust首先查看当前上下文,然后查看每个父上下文,直到没有更多父项要搜索.如果没有找到键,Dust什么都不做(除非你使用Exists或Not Exists Section) .如果Dust找到密钥,它将停止搜索并使用给定的值.那不是太陌生了吧?这就是JavaScript在执行环境中查找变量的方式.

但是,当使用路径时,除了向树查找树之外,Dust只会查看子项.用一个例子可以很好地说明这一点.

JSON:

{
  "i18n": {
    "firstname": "First Name"
  },
  "name": "My Dust Template",
  "firstname": "Surprise!",
  "people": [
    {
      "name": {
        "firstname": "Moe",
        "lastname": "Howard"
      }
    },
    {
      "name": {
        "firstname": "Curly",
        "lastname": "Howard"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

而尘埃:

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}
Run Code Online (Sandbox Code Playgroud)

[编辑]:有关更多信息,请查看来自Dust的LinkedIn分支的这个wiki页面:https://github.com/linkedin/dustjs/wiki/Where-else-does-Dust-search-if-the-value- IS-不限定%3F-AKA-防尘作用域