admin管理员组

文章数量:1287593

I have an object in witch some of the values are strings containing spaces. Something like this:

object = {
 "group of people": [
  {
   (...)
  }
 ],
 "another group of people": [
  {
   (...)
  }
 ]
}

And I'm trying to use it with the handlebars helper block in my view (index.hbs) like this:

{{#each group of people}}
 (...)
{{/each}}

But I get an error (of course), because of the spaces on "group of people". I've tried the following cases without any success:

{{#each "group of people"}}
{{#each 'group of people'}}
{{#each group%20of%20people}}
{{#each groupofpeople}}
{{#each group of people}}

Any idea on how to get this working?

I have an object in witch some of the values are strings containing spaces. Something like this:

object = {
 "group of people": [
  {
   (...)
  }
 ],
 "another group of people": [
  {
   (...)
  }
 ]
}

And I'm trying to use it with the handlebars helper block in my view (index.hbs) like this:

{{#each group of people}}
 (...)
{{/each}}

But I get an error (of course), because of the spaces on "group of people". I've tried the following cases without any success:

{{#each "group of people"}}
{{#each 'group of people'}}
{{#each group%20of%20people}}
{{#each groupofpeople}}
{{#each group of people}}

Any idea on how to get this working?

Share Improve this question asked Feb 16, 2017 at 2:13 Diogo CapelaDiogo Capela 6,5905 gold badges28 silver badges37 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 14

To use a property that has spaces, you can decorate it with []. e.g. Given helpers:

obj = {
  'property with spaces': 'hello'
};

Template:

<p>{{[property with spaces]}}</p>

Would generate:

<p>hello</p>

The strings don't matter, they're values to handlebars. Consider this:

  <ul>
    {{#each object}}
      <li>{{@key}}: {{this}}<li>
    {{/each}}
  </ul>

You'll get a set of list items for each key in your object. The keys like 'group of people' will print out where I've put @key and the value for that key will be printed where there is this, though in your case that's another array so obviously you'll want to further transform that.

I have something to add 5 years later for whoever gets stuck like me. I struggled to add an object key containing spaces Spaced Key as a form name:

{{#each ObjectKey}}
<label>{{@key}}<input name={{@key}}></label>
{{/each}}

Would render as

<label>Spaced Key<input name="Spaced" Key></label>

It could not be solved with segment-literal notation [], triple-stash {{{ }}} or both. The only solution was to register a helper

Handlebars.registerHelper('setName', function (inputName) {
    return `name="${inputName}"`;
});

Then set the template as such

{{#each ObjectKey}}
<label>{{@key}}<input {{{setName @key}}}></label>
{{/each}}

Hope that saves someone the hours I spend troubleshooting.

本文标签: javascriptHow to reference an element with spaces in handlebars on nodejsStack Overflow