我正在尝试创建自己的 Handlebars 助手,但在传递参数时遇到问题。对于上下文,我正在尝试破解 Ghost ( http://tryghost.org ),但我怀疑这是一个更普遍的 Handlebars 问题。
工作
首先,一个工作示例。这是我的模板的相关部分:
<h1>{{myHelper}}</h1>
这是我的 Handlebars.registerHelper
方法(Ghost 重命名了它,但它是一样的):
ghost.registerThemeHelper("myHelper", function() {
console.log(this.posts[0].title); // outputs "Welcome to Ghost" to console
return this.posts[0].title; // returns "Welcome to Ghost"
})
不工作
下面是我想要实现的。模板:
<h1>{{myHelper "title"}}</h1>
<h3>{{myHelper "slug"}}</h3>
当我尝试将参数传递给方法时,它无法替换变量:
ghost.registerThemeHelper("myHelper", function(myData) {
console.log(this.posts[0].myData); // outputs "undefined" to console
return this.posts[0].myData; // returns nothing
})
传递像“title”这样的字符串以便在表达式中对其求值的正确方法是什么?
对于任何好奇的 Ghost 用户,我在 ghost/core/server.js
的 activateTheme()
函数中注册了我自己的助手
最佳答案
arguments
的 console.log
输出:
{ '0': 'title', '1': { hash: {}, data: { blog: [Object] } } }
建议当您说 {{myHelper "title"}}
时,助手的第一个参数是 'title'
。如果 this.posts[0]
是您感兴趣的帖子,那么您会想要查看:
this.posts[0][myData]
当 myData
为 'title'
时,获取 this.posts[0]
的 title
属性。请注意,方括号用于访问普通数组(由非负整数索引)和对象(由字符串索引)。
一点时间在MDN JavaScript引用可能会有帮助。
关于javascript - 如何在 Handlebars 帮助器表达式中将字符串作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18937438/