Search code examples
javascriptember.jshandlebars.js

How to get an access in EmberJS template to a value of the object property within key stored in other variable?


I want to iterate over object properties in the specific order. I've prepared jsbin example of my usecase (with Ember.js and Handlebars). I can't find a way to make handlebars analog of

var months = ['2014-01-01', '2014-02-01', '2014-03-01'];

var datesByMonth = {
  '2014-03-01' : [ // march
    { date: '2014-03-10' },
    { date: '2014-03-20' },
    { date: '2014-03-21' }
  ],
  '2014-01-01' : [ // january
    { date: '2014-01-10' },
    { date: '2014-01-20' },
    { date: '2014-01-21' }
  ],
  '2014-02-01' : [ // february
    { date: '2014-02-10' },
    { date: '2014-02-20' },
    { date: '2014-02-21' }
  ],
};

var monthsCount = months.length;

for(var i = 0; i < monthsCount; ++i) {
  var month = months[i];
  console.log(month);
  
  var dates = datesByMonth[month];
  var datesCount = dates.length;
  
  for(var j = 0; j < datesCount; ++j) {
    var obj = dates[j];
    
    console.log('   ', obj.date);
  }
}

So, The question is How to get an access to a value of the object property within key stored in other variable?

P.S. Versions: EmberJS v1.9.1, Handlebars v2.0.0

P.S.S Sorry for my English


Solution

  • I've just noticed that EmberJS since v1.10.0 uses HTMLBars as Handlebars template compiler. HTMLBars compiler allow to use helpers as subexpressions (In Ember v1.9.1 & Handlebars v2.0.0 the helper outputs his result directly to html, not to parent helper), so I've created handlebars analog of lookup helper:

    Ember.Handlebars.registerBoundHelper('lookup', function(obj, key) {
      return obj && obj[key];
    });
    

    The helper allows to write such template code:

    <ul>
      {{#each month in monthSorting}}
        <li>
          <h2>{{month}}</h2>
          <ul>
            {{#each obj in (lookup model month)}}
              <li>{{obj.date}}</li>
            {{/each}}
          </ul>
        </li>
      {{/each}}
    </ul>
    

    The helper solves the problem of accessing an inner property of an object by using a dynamic key name.