简体   繁体   English

把手js对象迭代

[英]Handlebars js object iteration

In my gulpfile I'm defining a memberInfo array of objects to pass to the template: 在我的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'));
}

What I want to do on my template is say "for each object in memberInfo, if the list_id is equal to 1, display these fields" 我要在模板上执行的操作是说“对于memberInfo中的每个对象,如果list_id等于1,则显示这些字段”

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

What is the proper way of doing this? 正确的做法是什么? I'm brand new to gulp and handlebars and the explanations I've found don't seem to make any sense in this context. 我是不熟悉gulp和把手的新手,在这种情况下,我发现的解释似乎没有任何意义。 Handlebar-helpers has a nifty comparison operator {{#is }} so I wrote this code, but it obviously isn't set up properly: 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>

I apologize for this half assed comment, but I don't have time to fully answer it right now. 对于半点评论,我深表歉意,但现在我没有时间完全回答。 I had a similar situation, but I was looking to get the number of items that match and render that. 我也有类似的情况,但是我一直在寻找匹配并渲染的项目数量。 Here's the handlebars helper, and I hope the idea of this helps. 这是车把的帮手,希望这一想法对您有所帮助。 Let me know if it doesn't and I can add some more context soon. 让我知道是否可以,我可以尽快添加更多上下文。

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;    
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM