Handlebars js对象迭代

时间:2017-07-14 19:40:46

标签: javascript handlebars.js handlebarshelper

在我的gulpfile中,我定义了一个要传递给模板的memberInfo对象数组:

var gulp = require('gulp');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
var handlebars_helpers = require('handlebars-helpers')(); 
//http://assemble.io/helpers/helpers-html.html
var _ = require('underscore');

gulp.task('default', function () {
    var templateData = {
        memberInfo: [
            {"member_email": "amy@email.com", "list_id": "2", "name": "obsession cologne 3 oz", "brand": "", "price": "55.99"},
            {"member_email": "amy@email.com", "list_id": "1",  "name": "red plaid skirt", "brand": "versace", "price": "55.99"},
            {"member_email": "amy@email.com", "list_id": "1", "name": "black ruffle shirt", "brand": "versace", "price": "47.99"},
        ]
    }

    options = {
        helpers: _.extend(handlebars_helpers) 
    }

    return gulp.src('template/email.handlebars')
        .pipe(handlebars(templateData, options))
        .pipe(rename('email.html'))
        .pipe(gulp.dest('output'));
}

我想在模板上做的是对于memberInfo中的每个对象说"如果list_id等于1,则显示这些字段"

{{name}}
{{brand}}
{{price}}

这样做的正确方法是什么?我是gulp和把手的全新品牌,我发现的解释似乎在这方面没有任何意义。 Handlebar-helpers有一个漂亮的比较运算符{{#is }},所以我编写了这段代码,但显然没有正确设置:

<ul>
  {{#each memberInfo}}
    {{#each this}}
        <li>Key: {{@key}} Value = {{this}}</li>
        {{#is @key 'list_id'  }} 
            {{#is this 1 }}
               {{name}}
               {{brand}}
               {{price}}
               //Nothing is accessible here except this, as far as i can tell, so none of these values render

            {{/is}}
        {{/is}}

    {{/each}}
  {{/each}}
</ul>

1 个答案:

答案 0 :(得分:0)

我为这一半评论道歉,但我现在没时间完全回答。我有类似的情况,但我希望获得匹配并呈现的项目数量。这是车把助手,我希望这个想法有所帮助。如果它没有,请告诉我,我可以尽快添加一些上下文。

exports.filterLength = function (object, property, value, options) {
  var ret = 0;

  for (var i = 0, j = object.length; i < j; i++) {
    if (object[i][property] === value) {
      ret = ret + 1;
    }
  }
  return ret;    
};