Reputation: 16163
I am rendering a Nunjucks template multiple times in the browser:
$.ajax({
url: '/products',
contentType: 'application/json',
type: 'GET',
success: function(response) {
var $tableBody = $('#products-table-body');
response.products.forEach(function(product) {
$tableBody.append(
nunjucks.render( '_item-row.html', { id: product.id, name: product.name } )
);
});
}
});
That is creating an HTTP request for each iteration which just receives the same template each time, which seems unnecessary if I just want to use the same template to insert different values for each iteration.
How can I only request the template once and then use that single template request to fill in the values in each iteration?
Upvotes: 3
Views: 3406
Reputation: 16163
Thanks to the helpful Nunjucks documentation, I figured it out.
var env = new nunjucks.Environment(new nunjucks.WebLoader('../views'));
$.ajax({
url: '/products',
contentType: 'application/json',
type: 'GET',
success: function(response) {
var $tableBody = $('#products-table-body');
var template = env.getTemplate('_item-row.html');
response.products.forEach(function(product) {
$tableBody.append(
nunjucks.render( template, { id: product.id, name: product.name } )
);
});
}
});
Upvotes: 2