splattne
splattne

Reputation: 104040

Applying a Handlebars template in JavaScript code

I'm trying to use Ember's Handlebars engine for a not UI related purpose. I have a series of text templates (basically placeholders + static text), like

Order number {{number}} / {{year}}

I'm using the following code in a controller function (simplified here for the sake of the example):

formattedTitle: function(order) {
   var orderTitle = "Order number {{number}} / {{year}}";
   var template = Handlebars.compile(orderTitle);
   return template(order);
}

offer is a Ember.data record, containing both fields.

When I run the function the resulting string only contains the static text:

Order number /

It only works with the {{id}} property, probably because you can do order.id on the Ember.data record, but not order.number (you have to use get - order.get("number"))

Any idea how to solve this?

Upvotes: 2

Views: 113

Answers (2)

intuitivepixel
intuitivepixel

Reputation: 23322

Try something like this:

function formattedTitle(order) {
  var number = order.get('number');
  var year = order.get('year');
  var orderContext = { number: number, year: year };
  var orderTitle = "Order number {{number}} / {{year}}";
  var template = Handlebars.compile(orderTitle);
  var output = template(orderContext);

  return output;
}

Upvotes: 2

CraigTeegarden
CraigTeegarden

Reputation: 8251

You could use the Ember's Object.getProperties() to pull multiple properties into a simple javascript object and pass that in as the Handlebars context. Not sure that this is the best way to do this, though...

formattedTitle: function() {
    var order = Ember.Object.create({number: 1, year: 2013});
    // retrieve the properties ahead of time using Ember getter
    var orderContext = order.getProperties(['number', 'year']);
    var orderTitle = "Order number {{number}} / {{year}}";
    var template = Handlebars.compile(orderTitle);
    var output = template(order);
    return output;
}

JSBin example

Upvotes: 3

Related Questions