Handlebars - 如何获取当前上下文的键?

问题描述 投票:0回答:1

我有一些这样的数据:

{myData: {"My Key": [1,2], "The Other Key": [3,4]}}

我将数据作为上下文传递(在我的应用程序中,我将其作为部分数据进行传递,但

{{with}}
应该做同样的事情:

{{#with myData.[My Key]}}
    hello? {{@key}}  ?
{{/with}}

我知道这行得通,因为如果我添加

{{#each .}}{{this}}{{/each}}
它会打印出
12
.

如何从

{{with}}
块中访问“我的密钥”?放置
{{@key}}
什么都不做。尝试
{{../@key}}
会导致错误。

编辑:这行得通

const template = Handlebars.compile(`
  {{> myPartial key="My Key"}}
`);

Handlebars.registerPartial('myPartial', 'KEY:{{key}}|DATA:{{lookup myData key}}|HARDCODEDATA:{{myData.[My Key]}} ?');

const data = {
  myData: {
    "My Key": 'dog',
    "The Other Key": 'cat'
  }
};

const output = template(data);

document.body.innerHTML = output;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>

handlebars.js
1个回答
0
投票

无法获取您提供的示例中的密钥,因为没有上下文是

myData
对象密钥的迭代。
#with
块中的上下文是
myData["My Key"]
的值,它的父上下文是
myData
.

但是,在您的帖子中,您声明

#with
助手应该与部分助手相同;但有一个关键的区别。部分允许你传递参数。因此,您可以在调用部分时简单地将密钥作为参数传递:

const template = Handlebars.compile(`
  {{> myPartial myData.[My Key] key="My Key"}}
`);

Handlebars.registerPartial('myPartial', 'hello? {{key}} ?');

const data = {
  myData: {
    "My Key": [1, 2],
    "The Other Key": [3, 4]
  }
};

const output = template(data);

document.body.innerHTML = output;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.