【问题标题】:How to use a collection in a handlebars helper如何在车把助手中使用集合
【发布时间】:2013-12-11 02:34:46
【问题描述】:

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

这是我的助手:

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

peeps.forEach(function(persons){

  return [ 
  {label:persons.firstName , value:persons.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 用于获取集合中的每个名字。如何在不使用把手帮助器的情况下使用流星语法来处理自动表单?

谢谢

【问题讨论】:

  • 你为什么使用Handlebars.registerHelper?你读过文档吗?只需通过在模板上定义一个函数来添加一个助手 - Template.myTemplate.myHelper = function() {};

标签: javascript meteor handlebars.js


【解决方案1】:

正如 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 来返回修改后对象的单个数组。

【讨论】:

    【解决方案2】:

    这就是最终对我有用的东西:

    车把助手:

    Handlebars.registerHelper("personSelect", function() {
    
    peeps = Persons.find();
    
    
    people = peeps.map(function(peeps) {
    
    return {label:peeps.fullName, value:peeps.fullName };
    
    });
    return people;
    });
    

    对于自动生成模板:

     <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。如果有人知道该怎么做,我会全力以赴。

    【讨论】:

      猜你喜欢
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 2015-12-18
      • 2013-02-05
      • 2019-01-05
      相关资源
      最近更新 更多