Search code examples
node.jsnunjucks

render nunjucks template in the browser


Part of the nunjucks template consists of variables which I would like to set after the page was sent to the browser. Currently it would also needs to import other templates.

Do I need to preinclude the other imported templates?


Solution

  • The best way to to this is by using a custom loader.

    First you send the unrendered template to the client. (You don't need to prerender the imports) Then you write a custom loader where you can define how the imports should be loaded.

    Example (I used type as an extra GET parameter to define that the template should not be rendered):

    var customLoader = {getSource:"",async:true};
    customLoader.getSource = function(name, cb) {
        var reqPath = window.location.protocol + "//" + window.location.host + "/" + name + "?type=view";
        $.get(reqPath, (data) => {
            cb(null, {src:data, path:reqPath});
        }); 
    }
    
    var env = new nunjucks.Environment(customLoader);
    

    Then you can use the env callback to render the template:

    env.renderString(theInitialTemplate, yourJSONData, (err, res) => {
        console.log(res); //do something with the res variable
    });
    

    In this example I used an async loader. You can use new Promise to load both the model and the view and afterwards check with Promise.all to put both together and render the template.