javascriptmeteormeteor-blazespacebars

Meteor blaze template access object property by key without helper


I wonder if it is possible to achieve object access by property-string like

const obj = { foo:"bar" }
obj["foo"] // returns "bar"

via Blaze Spacebars (thus, without using a helper function).

I tried something like

{{#with obj}}
  {{this['foo']}}
{{/with}}

but it seems that it does not accept the squared brackets. Note: I can not just only type

{{this.foo}}

because the property name is dynamically given by another object as a value.


Solution

  • How about a helper function that returns the keys and another that takes in the object and key and returns the value?

    // JS
    Template.registerHelper('keys', function keys (object) {
      return Object.keys(object);
    });
    Template.registerHelper('pick', function pick (key, object) {
      return object[key];
    });
    
    // html
    <template name="foo">
      {{#each key in (keys obj)}}
        {{key}} - {{pick key obj}}
      {{/each}}
    </template>
    

    EDIT: Just noticed your headline says pretty explicitly "Without helper". I don't think this is possible without a helper