是否有内置的方法来循环对象的属性?

发布于 2024-12-29 10:39:59 字数 338 浏览 0 评论 0原文

是否有 Mustache / Handlebars 方式循环访问 object 属性?

那么,

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

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

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

Is there a Mustache / Handlebars way of looping through an object properties?

So with

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

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

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

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

无语# 2025-01-05 10:39:59

自 Handlebars 1.0rc1 起内置支持

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

如何使用它

对于数组:

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

对于对象:

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

请注意,只有传递 hasOwnProperty 测试将被枚举。

Built-in support since Handlebars 1.0rc1

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

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 hasOwnProperty test will be enumerated.

愛上了 2025-01-05 10:39:59

作为一个助手,它实际上很容易实现:

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

然后像这样使用它:

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

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 }}
泪痕残 2025-01-05 10:39:59

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

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

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

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

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

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

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:

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:

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

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

软糯酥胸 2025-01-05 10:39:59

这是 @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;
});

模板:

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

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

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 }}
情绪失控 2025-01-05 10:39:59

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

至于仅限车把的解决方案,我见过一些,我喜欢 https://gist.github.com/1371586 最好。

  • 它允许您迭代对象文字,而不必先重构它们,并且
  • 它使您可以控制所谓的关键变量。对于许多其他解决方案,您必须小心使用名为 'key''property' 等的对象键。

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

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

  • 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.
鹊巢 2025-01-05 10:39:59

代码的顺序显示特定字段

感谢 Ben 的解决方案,我的用例仅按对象

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

源对象:

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

模板:

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

输出:

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

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

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
杀お生予夺 2025-01-05 10:39:59

这是 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'
        }
    }
};

模板:

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

输出:(

color: blue
color: red

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

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

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.

淡淡绿茶香 2025-01-05 10:39:59

我使用的是旧版本的车把 1.0.beta.6,我认为在 1.1 - 1.3 期间添加了此功能,因此更新到 1.3.0 解决了该问题,以下是用法: 用法

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

I was using old version 1.0.beta.6 of 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:

Usage:

{{#each object}}
  Key {{@key}} : Value {{this}}
{{/people}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文