Mustache.js - 显示键而不是值 [英] Mustache.js - display key instead of value

查看:70
本文介绍了Mustache.js - 显示键而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用这些数据: http://pastie.org/3231052 - 如何显示键而不是使用胡须或把手的价值?

  [{interval:2012-01-21,
advertiser:广告客户1,
offer:人寿保险,
cost_type:CPA,
revenue_type:CPA,
... etc ...
}]


解决方案

如果你想显示键值对,你可以在Handlebars中写一个帮助器。

Handlebars.registerHelper('eachkeys' ,function(context,options){var fn = options.fn,inverse = options.inverse; var ret =; var empty = true; for(key in context){empty = false; break;} if(!empty ){for(key in context){ret = ret + fn({'key':key,'value' :context [key]});}} else {ret = inverse(this); }); $(function(){var data = {interval:2012-01-21,advertiser:Advertisers 1,offer:Life Insurance,cost_type :CPA,revenue_type:CPA}; var source = $(#template)。html(); var template = Handlebars.compile(source); $('#content')。html(template ({'data':data}));});

< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< script src =https:/ -template> {{#eachkeys data}}< li> {{this.key}} - {{this.value}}< / li> {{/ eachkeys}}< / script>< div id =content>< / div>

p>

编辑



似乎并不完全符合您的要求,但有可能拿出一个帮手来做这个伎俩。


I am using this data here: http://pastie.org/3231052 - How can I display the key instead of the value using Mustache or Handlebars?

[{"interval":"2012-01-21",
  "advertiser":"Advertisers 1",
  "offer":"Life Insurance",
  "cost_type":"CPA",
  "revenue_type":"CPA",
  ... etc ...
}]

解决方案

If you want to display key-value pairs, you can write a helper in Handlebars.

Handlebars.registerHelper('eachkeys', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var ret = "";

  var empty = true;
  for (key in context) { empty = false; break; }

  if (!empty) {
    for (key in context) {
        ret = ret + fn({ 'key': key, 'value': context[key]});
    }
  } else {
    ret = inverse(this);
  }
  return ret;
});

$(function() {
    var data = {"interval":"2012-01-21",
      "advertiser":"Advertisers 1",
      "offer":"Life Insurance",
      "cost_type":"CPA",
      "revenue_type":"CPA"};
                
    var source   = $("#template").html();
    var template = Handlebars.compile(source);
    $('#content').html(template({'data': data}));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta2/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
    {{#eachkeys data}}
    <li>{{this.key}} - {{this.value}}</li>
    {{/eachkeys}}
</script>
<div id="content">
</div>

EDIT

Seems like this isn't quite what you want, but it's possible to come up with a helper that will do the trick.

这篇关于Mustache.js - 显示键而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆