Search code examples
javascripthandlebars.jsinformation-hiding

Retrieving Private Array Data in Handlebars.js Template


Given this plain JavaScript construct:

var MyObject = function() {
  var privateArray = [
    { name: 'one' },
    { name: 'two' }
  ];
  this.returnPrivate = function(index) {
    return privateArray[index];  
  };
};
var obj = new MyObject();

Within a handlebars template I would like to be able to print the name property of an object at a particular index of the privateArray using the returnPrivate function.

// This of course does not work.
<p>{{returnPrivate(1).name}}</p>

I am just starting out with handlebars.js, so there might already be a standard way of doing this. Or this might be trying to build too much logic into the template and be going against what handlebars is all about.


Solution

  • I have come up with a Helper that does what I need it to, but I would very much appreciate some feedback as to whether this is the best way to solve this type of problem with Handlebars.

    /**
     * Given the name of a function that returns an array value, this helper
     * returns the value at a given index.  Optionally it takes a property name
     * in case the array value at the given index is itself an object.
     */
    Handlebars.registerHelper('eqf', function(func, index, prop) {
      if (typeof prop === 'string') {
        return func(index)[prop];
      } else {
        return func(index);
      }
    });
    

    Usage for question example:

    <p>{{eqf returnPrivate 1 "name"}}</p>