简体   繁体   中英

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');
});

thx for any help

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM