本文介绍了如何将任意的模板变量传递给一个句柄助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模板中迭代一个简单的数组:

  {{#chapter#中的每一章}} 
< li> {{chapter}} {{test chapter}}< / li>
{{/ each}}

chatperList 这里就是 [1,2,3,4,5] 。我做了一个Handlebars帮手:

  Ember.Handlebars.registerHelper('test',function(chapter){
return this.get('list.selectedChapter')== chapter
?'selected'
:'';
});

但帮助函数中的变量只是字符串章。如何访问实际变量本身?

解决方案

这看起来像Ember中的一个错误(仍然是最新的v1.0) ...你不能将变量传递给#each内的帮助器,或者你可以得到: -

  TypeError:Object。 defineProperty调用非对象

我刚刚找到一个使用options.data的内容的解决方法,但它意味着你需要引用你所传递的对象,如果它在#each(通知'颜色'而不是颜色下面)



模板:

 < ul> 
< li> {{helpme color'lorry'}}< / li>

{{#模型中的#each颜色}}
< li> {{helpme'color''lorry'}}< / li>
{{/ each}}
< / ul>

助手:

 code> Ember.Handlebars.helper('helpme',function(color,vehicle,opts){
var str = color;
if(typeof opts.data.keywords [color] == ='string'){
str = opts.data.keywords [color];
}
返回新的Ember.Handlebars.SafeString(str +'_'+车辆);
});

...看到我的



编辑:旧版本的Ember使用 Ember.Handlebars.registerHelper()而不是
Ember.Handlebars.helper()


I'm iterating over a plain array in my template:

{{#each chapter in chapterList}}
  <li>{{ chapter }} {{ test chapter }}</li>
{{/each}}

chatperList here is, say, [1, 2, 3, 4, 5]. I've made a Handlebars helper:

Ember.Handlebars.registerHelper('test', function(chapter) {
  return this.get('list.selectedChapter') == chapter
    ? 'selected'
    : '';
});

but the chapter variable in the helper function is simply the string "chapter". How can I access the actual variable itself?

解决方案

This looks like a bug in Ember (still in the latest v1.0) ... you can't pass a variable to a helper inside an #each or you get:-

TypeError: Object.defineProperty called on non-object

I just found a workaround using the contents of options.data, but it means you need to quote the object you're passing if it's inside an #each (notice 'color' instead of color below)

Template:

<ul>
  <li>{{helpme color 'lorry'}}</li>

{{#each color in model}}
  <li>{{helpme 'color' 'lorry'}}</li>
{{/each}}
</ul>

Helper:

Ember.Handlebars.helper('helpme', function (color, vehicle, opts) {
    var str = color;
    if (typeof opts.data.keywords[color] === 'string') {
        str = opts.data.keywords[color];
    }
    return new Ember.Handlebars.SafeString(str + '_' + vehicle);    
});

... see my JSFiddle

EDIT: older versions of Ember use Ember.Handlebars.registerHelper() instead of Ember.Handlebars.helper()

这篇关于如何将任意的模板变量传递给一个句柄助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 19:16