Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Handlebars partial from jQuery

Say I have the following partial in my JavaScript:

Handlebars.registerPartial('itemcount', '<div class="row"><div class="count span1">{{count}}</div><div class="notes span4">{{notes}}</div>/div>');

and use it like this:

    {{#each item_counts}}
      {{> itemcount }}
    {{/each}}

How could I use the 'itemcount' partial in a jQuery callback like (something like)?

$.ajax({
  url: '/arc/v1/api/item_counts/',
  type: 'POST',
  data: {item_count:{inventory_item_id: id_val, count:count_val, date:date_val, notes:notes_val}},
  dataType: 'json'
}).done(function(r){
  var item_count=r.item_count;
  // here is where I would want to get access to this and 
  //var template = Handlebars.compile(source, item_count); ????

  $('.itemcount-header').after('this is after');
});
like image 797
timpone Avatar asked Apr 17 '26 10:04

timpone


1 Answers

When you register a partial, the source is stored in Handlebars.partials under the associated key. You can then compile this source at runtime and use the resulting function as a regular template:

$.ajax({
    // ...
}).done(function(r){
    var item_count = r.item_count;
    var markup = Handlebars.compile(Handlebars.partials.itemcount, {
        count: item_count
    });
});

You can also register a precompiled template as a partial if you reuse it multiple times:

Handlebars.registerPartial('itemcount',  Handlebars.compile(src));

$.ajax({
    // ...
}).done(function(r){
    var item_count=r.item_count;
    var markup = Handlebars.partials.itemcount({
        count: item_count
    });
});

Note that you don't have to change anything in your master template when you register compiled partials.

And a demo http://jsfiddle.net/nikoshr/9La3p/

like image 195
nikoshr Avatar answered Apr 19 '26 00:04

nikoshr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!