Javascript 句柄:从帮助程序返回哈希
我可以从车把助手处返回哈希吗?我试过这个: 在我看来:Javascript 句柄:从帮助程序返回哈希,javascript,backbone.js,coffeescript,handlebars.js,Javascript,Backbone.js,Coffeescript,Handlebars.js,我可以从车把助手处返回哈希吗?我试过这个: 在我看来: initialize: -> super this.hash = {key1: 'test1', key2: 'test2'} Handlebars.registerHelper 'show', => return this.hash {{show.key1}} this.showAttributes = {title: 'title1', author
initialize: ->
super
this.hash = {key1: 'test1', key2: 'test2'}
Handlebars.registerHelper 'show', =>
return this.hash
{{show.key1}}
this.showAttributes = {title: 'title1', author: 'author1'}
Handlebars.registerHelper 'show', (cond) =>
return cond.fn(this.showAttributes)
{{#show}}
{{title}}
{{author}}
{{/show}}
在模板中:
initialize: ->
super
this.hash = {key1: 'test1', key2: 'test2'}
Handlebars.registerHelper 'show', =>
return this.hash
{{show.key1}}
this.showAttributes = {title: 'title1', author: 'author1'}
Handlebars.registerHelper 'show', (cond) =>
return cond.fn(this.showAttributes)
{{#show}}
{{title}}
{{author}}
{{/show}}
我做错了什么?谢谢 车把将看到:
{{show.key1}}
试图访问show
变量的key1
属性时,它不会知道在这种情况下show
应该指向您的show
助手。这只是车把语法的一部分,我认为你对此无能为力
但是,您可以将key1
作为参数传递给show
助手。如果按以下方式定义辅助对象:
Handlebars.registerHelper 'show', (key, context) =>
@hash[key]
{{show "key1"}}
然后像这样使用它:
Handlebars.registerHelper 'show', (key, context) =>
@hash[key]
{{show "key1"}}
然后你会得到你期望的结果
演示:找到了另一种方法。您可以将上下文传递给条件帮助器,如下所示:
Handlebars.registerHelper 'show', (key, context) =>
@hash[key]
{{show "key1"}}
助手:
initialize: ->
super
this.hash = {key1: 'test1', key2: 'test2'}
Handlebars.registerHelper 'show', =>
return this.hash
{{show.key1}}
this.showAttributes = {title: 'title1', author: 'author1'}
Handlebars.registerHelper 'show', (cond) =>
return cond.fn(this.showAttributes)
{{#show}}
{{title}}
{{author}}
{{/show}}
在模板中:
initialize: ->
super
this.hash = {key1: 'test1', key2: 'test2'}
Handlebars.registerHelper 'show', =>
return this.hash
{{show.key1}}
this.showAttributes = {title: 'title1', author: 'author1'}
Handlebars.registerHelper 'show', (cond) =>
return cond.fn(this.showAttributes)
{{#show}}
{{title}}
{{author}}
{{/show}}
很好用