0

我正在尝试使用 Meteor TemplateHelpers 和 Handlebars填充select元素。option

模板

<template name="newTransaction">
...
<select name="productNameSelect">
{{{ getProductOptions }}} 
</select>
...
</template>

帮手

Template.newTransaction.getProductOptions = function () {
    //Get all products for drop-down
    var count = 0;
    var optionsHTML = "";
    var options = ProductCollection.find({});
    options.forEach( function( product )
    {
      var newOption = "<option value='" + product.productID + "' >" + product.name + "</option>";
      optionsHTML += newOption;
      ++count;
      if( count == options.count() )
      {
        console.log("Products returned for client:" + optionsHTML )
        return optionsHTML;
      }
    });
};

在浏览器 JavaScript 控制台中,打印了正确的控制台日志文本,但我的选择列表中没有任何选项添加到 DOM。

我所有的其他小助手功能都可以正常工作,尽管它们要简单得多并且可能不会花费太多时间。如何正确呈现选项元素?

4

1 回答 1

1

这是因为forEach您使用了迭代器。当您返回回调时,它会返回到forEach迭代而不是您想要的帮助器。

您还需要记住,使用 Meteor 会有一个自然延迟,因为首先加载 html 和 js,然后很快就会加载数据。

You could still use forEach but ensure you return data after the loop and not in it. I'm not 100% sure of your intentions so this may not work as you intend but you

var options = ProductCollection.find({});
var html = "";    

options.forEach( function( product )
{
  var newOption = "<option value='" + product.productID + "' >" + product.name + "</option>";
  optionsHTML += newOption;
});

return optionsHTML;

Also dont forget to use three mustaches {{{getProductOptions}}} and not two since you're providing back raw HTML

Also have you considered using an {{each}} loop?

Template.newTransaction.getProductOptions = function () { return ProductCollection.find() }

then you could do this in your html instead

{{#each getProductOptions}}
    <option value="{{productID}}">{{name}}</option>
{{/each}}
于 2013-09-26T15:53:22.373 回答