Search code examples
node.jsexpressasynchronouskeystonejsnunjucks

Nunjucks Async Rendering with Keystone View


In an Express-based app, I'm running an async function to fetch image source from a database and render them into a Nunjucks view engine

Nunjucks is rendering the following in the DOM

<img src="[object Promise]">

I have already enabled Nunjucks's async rendering with web: { async: true } and enabled the nunjucks async api with a callback like so

// controller.js (KeystoneJS app)
view.render('index', function (err, res) {
    console.log('err at index render', err); // undefined
    return res;
});

How can i get the resolved value of my async function?


Solution

  • As I understand it, Nunjucks doesn't support asynchronous render directly. You can use asynchronous filters to get it. Maybe I'm wrong.

    Imho, use feature with Be Careful! mark is a not good idea.


    // template.njk
    Hello {{user_id | find | attr('name') }}!
    
    // app.js
    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    
    // Async filter
    env.addFilter('find', function(a, cb) {
        setTimeout(function () {
            cb(null, {
                name: 'Smith'
            });
        }, 10);
    }, true)
    
    // Sync filter
    env.addFilter('attr', function(obj, attr) {
        return obj && attr && obj[attr];
    });
    
    env.render('template.njk', 
        {user_id: 1}, // pass sync vars
        function(err, res) {
            if (err)
               return;
    
            console.log(res);
            return res
        }
    );