我正在为我的模板使用 Handlebars。有没有一种方法可以在使用助手的地方使用模板中的值?
重要的是给定的值是一个字符串,然后是值。
例子:
// Template.html
<p>{{myHelper 'This is an awsome {name}'}}</p>
Helper.js
Handlebars.registerHelper('myHelper', function(string){
// string is 'This is an awsome {name}' AND it is important that {name} is a string and at this point not the real value
var myNewString = string.replace(\{name}\, Handlebars.getValueByKey(name));
return myNewString
});
如果 name 是“Test”,则返回值将是 This is an awsome Test
name 的值在该模板的另一个 Helper 中给出,其中定义“name”是字符串形式的“Test”。
我正在寻找类似于我在示例中使用的函数 - getValueByKey
有没有典型的方法来做到这一点?我在官方文档中没有找到类似的内容。
编辑: 抱歉 - 我不知道为什么代码框中的示例看起来像这样。
最佳答案
你很接近。关键在于将您想要的内容准确传递给模板:
// Template.html
<p>{{myHelper 'This is an awesome' name}}</p>
Helper.js
Handlebars.registerHelper('myHelper', function(string, name){
// string is 'This is an awesome'
// value of {name} is passed as another value
// If you wanted to do other things with the {name} you could
// do that in the function below
var myNewString = string + name;
return myNewString
});
希望这更接近您要找的东西。
关于javascript - 从 Handlebars 助手中的模板获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016344/