Javascript Handlebars/Mustache - 是否有内置的方法来循环遍历对象的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9058774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:32:09  来源:igfitidea点击:

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

javascripthandlebars.jsmustache

提问by Ben

As the title of question says, is there a mustache/handlebars way of looping through an objectproperties?

正如问题的标题所说,是否有循环遍历对象属性的胡须/把手方式?

So with

所以与

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
}

Can I then do something in the template enginethat would be equivalent to

然后我可以在模板引擎中做一些相当于

for(var prop in o)
{
    // with say, prop a variable in the template and value the property value
}

?

?

回答by Jon

Built-in support since Handlebars 1.0rc1

自 Handlebars 1.0rc1 以来的内置支持

Support for this functionality has been addedto Handlebars.js, so there is no more need for external helpers.

对这个功能的支持已经添加到 Handlebars.js,因此不再需要外部助手。

How to use it

如何使用它

For arrays:

对于数组:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

对于对象:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnPropertytest will be enumerated.

请注意,只有通过hasOwnProperty测试的属性才会被枚举。

回答by Ben

It's actually quite easy to implement as a helper:

作为助手实际上很容易实现:

Handlebars.registerHelper('eachProperty', function(context, options) {
    var ret = "";
    for(var prop in context)
    {
        ret = ret + options.fn({property:prop,value:context[prop]});
    }
    return ret;
});

Then using it like so:

然后像这样使用它:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

回答by Amit

EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answerabove. When working with plain Mustache, the below still applies.

编辑: Handlebars 现在有一个内置的方法来完成这个;请参阅上面选择的答案。使用普通 Mustache 时,以下内容仍然适用。

Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:

Mustache 可以遍历数组中的项目。所以我建议创建一个单独的数据对象,其格式设置为 Mustache 可以使用的方式:

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };

for (var prop in o){
  if (o.hasOwnProperty(prop)){
    mustacheFormattedData['people'].push({
      'key' : prop,
      'value' : o[prop]
     });
  }
}

Now, your Mustache template would be something like:

现在,您的 Mustache 模板将类似于:

{{#people}}
  {{key}} : {{value}}
{{/people}}

Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js

在此处查看“非空列表”部分:https: //github.com/janl/mustache.js

回答by flynfish

This is @Ben's answer updated for use with Ember...note you have to use Ember.getbecause context is passed in as a String.

这是@Ben 的答案,已更新以与 Ember 一起使用...请注意,您必须使用它,Ember.get因为上下文是作为字符串传入的。

Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
  var ret = "";
  var newContext = Ember.get(this, context);
  for(var prop in newContext)
  {
    if (newContext.hasOwnProperty(prop)) {
      ret = ret + options.fn({property:prop,value:newContext[prop]});
    }
  }
  return ret;
});

Template:

模板:

{{#eachProperty object}}
  {{key}}: {{value}}<br/>
{{/eachProperty }}

回答by mjumbewu

@Amit's answer is good because it will work in both Mustache and Handlebars.

@Amit 的回答很好,因为它适用于 Mustache 和 Handlebars。

As far as Handlebars-only solutions, I've seen a few and I like the each_with_keyblock helper at https://gist.github.com/1371586the best.

至于 Handlebars-only 解决方案,我已经看到了一些,我最喜欢https://gist.github.com/1371586 上each_with_key块助手。

  • It allows you to iterate over object literals without having to restructure them first, and
  • It gives you control over what you call the key variable. With many other solutions you have to be careful about using object keys named 'key', or 'property', etc.
  • 它允许您迭代对象字面量而无需先重构它们,并且
  • 它使您可以控制所谓的关键变量。对于许多其他解决方案,您必须小心使用名为'key'、 或'property'等的对象键。

回答by vincentlcy

Thanks for Ben's solution, my use case to display only particular fields in order

感谢 Ben 的解决方案,我的用例仅按顺序显示特定字段

with object

有对象

Code:

代码:

    handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
    var ret = "";
    var toDisplayKeyList = toDisplays.split(",");
    for(var i = 0; i < toDisplayKeyList.length; i++) {
        toDisplayKey = toDisplayKeyList[i];
        if(context[toDisplayKey]) {
            ret = ret + options.fn({
                property : toDisplayKey,
                value : context[toDisplayKey]
            });
        }

    }
    return ret;
});

Source object:

源对象:

   { locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}

Template:

模板:

{{#eachToDisplayProperty this "locationDesc,description,name"}}
    <div>
        {{property}} --- {{value}}
    </div>
    {{/eachToDisplayProperty}}


Output:

输出:

locationDesc --- abc
description --- def
name --- ghi

回答by Cuel

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

这是 mustacheJS 的一个辅助函数,无需预先格式化数据,而是在渲染期间获取它。

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

模板:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

输出:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

(顺序可能是随机的 - 它是一张地图)如果您知道所需的地图元素,这可能很有用。请注意虚假值。

回答by AamirR

I was using old version 1.0.beta.6of handlebars, i think somewhere during 1.1 - 1.3 this functionality was added, so updating to 1.3.0 solved the issue, here is the usage:

我使用的是旧版本1.0.beta.6的车把,我想在 1.1 - 1.3 的某个地方添加了这个功能,所以更新到 1.3.0 解决了这个问题,这是用法:

Usage:

用法:

{{#each object}}
  Key {{@key}} : Value {{this}}
{{/people}}