如何在车把助手中使用集合

时间:2013-12-11 02:34:47

标签: javascript meteor handlebars.js

我在Meteor.js上使用带有autoform的把手助手。我试图在我的表单上创建一个选择下拉框,但我希望选项来自集合而不是数组。我使用collection2包定义了我的集合“Persons”,并使用simple-schema定义了模式。我插入了两个具有firstName,lastName,fullName值的人。

这是我的助手:

Handlebars.registerHelper("personSelectOption", function(options) {
peeps = Persons.find().fetch();

peeps.forEach(function(persons){

  return [ 
  {label:persons.firstName , value:persons.firstName}
 ];
});
});

我正在尝试让下拉框显示我的集合中每个人的firstName,当我向集合中添加更多人员时,它会自动显示在下拉框中。

我知道我在这里错过了很多,但我是一个新的程序员,我能得到的任何帮助都会很棒。

谢谢!

我试图使用把手助手,因为我看到使用autoform的唯一好例子也是使用这个助手。 autoforms中的下拉框使用:

 <div class="form-group {{afHasError 'firstOptionSelect'}}">
        {{afFieldLabel 'firstOptionSelect'}}
        {{afFieldInput 'firstOptionSelect' firstOption="(Select Something)" options=personSelectOption}}
        {{#if afFieldIsInvalid 'firstOptionSelect'}}
        <span class="help-block">{{afFieldMessage 'firstOptionSelect'}}</span>
        {{/if}}
      </div>

选项是我试图让firstName出现的地方。 forEach是为了获得该系列中的每个名字。如何在不使用把手助手的情况下使用meteor语法处理自动形式?

由于

2 个答案:

答案 0 :(得分:0)

正如Cuberto所说,Meteor使您能够使用Meteor自己的语法向模板添加帮助程序。还不清楚你要对forEach块做什么,但这样的事情应该有效:

Template.myTemplate.helpers({
  personSelectOption: function() {
    return Persons.find().fetch();
  }
});

然后,您可以使用以下内容访问html中所需的信息:

<template name="myTemplate">
  <select>
    {{#each personSelectOption}}
      <option value="{{this.firstName}}">{{this.firstName}}</option>
    {{/each}}
  </select>
</template>

您可以在模板中访问所需的任何文档属性,而无需构建某些特殊结构并从帮助程序返回该属性。虽然如果你真的想这样做(因为你需要以某种方式改变属性),你应该使用map而不是forEach来返回修改对象的单个数组

答案 1 :(得分:0)

最终为我工作的是:

车把助手:

Handlebars.registerHelper("personSelect", function() {

peeps = Persons.find();


people = peeps.map(function(peeps) {

return {label:peeps.fullName, value:peeps.fullName };

});
return people;
});

对于autoform模板:

 <div class="form-group {{afHasError 'firstOptionSelect'}}">
        {{afFieldLabel 'firstOptionSelect'}}
        {{afFieldInput 'firstOptionSelect' firstOption="(Select Something)" options= personSelect  }}
        {{#if afFieldIsInvalid 'firstOptionSelect'}}
        <span class="help-block">{{afFieldMessage 'firstOptionSelect'}}</span>
        {{/if}}
      </div>

我没有使用Meteor Template.helper,因为我需要在autoform模板中显示模板。我还没有办法做到这一点所以我决定使用handlebars.helper。如果有人知道如何这样做,我会全力以赴。

相关问题