Reputation: 19979
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');
});
Upvotes: 3
Views: 1523
Reputation: 33364
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/
Upvotes: 1