Question

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.

Était-ce utile?

La 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>

Autres conseils

Handlebars has a special syntax for dealing with numeric or symbol identifiers, as described here. If you are able to pass the array index as a literal, you can use the following:

{{privateArray.[1].name}}

That only works if you restructure the object to make privateArray available to the template. If you really want to hide privateArray and force the template to use a function call, then you must use a helper.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top