node express handlebars 循环遍历
发布于 9 年前 作者 youarenode 7100 次浏览 最后一次编辑是 8 年前 来自 问答

request(‘http://xxxxxxxxxx.com/API.php’, function(error, response, body){ if(!error && response.statusCode == 200){ var data = JSON.parse(body); var noviceName = data.data.lists.novice[‘Name’];

		res.render('home', {
			noviceName : noviceName,
			
			node : 'v0.12.7'
		});
	}
});

我从后端API用node 拿过来的json数据 怎么给handlebars上无法循环遍历?

5 回复

错误是什么?

@leapon 没错误 但是我不能每个json属性都解出来再给 handlebars 吧? 我给到handlebars一个json对象 他不可以each 遍历吗?

@youarenode

遍历对象的属性

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}
Handlebars.registerHelper('each', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var i = 0, ret = "", data;

  if (options.data) {
    data = Handlebars.createFrame(options.data);
  }

  if(context && typeof context === 'object') {
    if(context instanceof Array){
      for(var j = context.length; i<j; i++) {
        if (data) { data.index = i; }
        ret = ret + fn(context[i], { data: data });
      }
    } else {
      for(var key in context) {
        if(context.hasOwnProperty(key)) {
          if(data) { data.key = key; }
          ret = ret + fn(context[key], {data: data});
          i++;
        }
      }
    }
  }

  if(i === 0){
    ret = inverse(this);
  }

  return ret;
});

看了下 handlebars 知道了 还不熟 谢谢

回到顶部