Search code examples
javascriptjqueryajaxnunjucks

Using Nunjucks in the browser, how do I only request a template once to iterate on using different values?


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.

enter image description here

How can I only request the template once and then use that single template request to fill in the values in each iteration?


Solution

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