mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.57k stars 638 forks source link

Not working {% include %} in condition with asynchronous loader #925

Open pkolt opened 7 years ago

pkolt commented 7 years ago

Bug nunjucks when using the asynchronous loader.

/templates/index.html:

<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {% if homePage %}
        {% include 'homePage.html' %}
    {% else %}
        {% include 'postList.html' %}
    {% endif %}
</body>
</html>

/templates/homePage.html

<h1>Home page</h1>

/templates/postList.html:

<h1>Post list</h1>

index.js:

const fs = require('fs');
const path = require('path');
const nunjucks = require('nunjucks');

const AsyncLoader = nunjucks.Loader.extend({
    async: true,

    init: function(dirname) {
        this.dirPath = path.resolve(dirname);
    },

    getSource: function(name, cb) {
        const filePath = path.join(this.dirPath, name);
        fs.readFile(filePath, 'utf-8', (err, data) => {
            if (err) return cb(err);
            const res = {src: data, path: filePath, noCache: true};
            cb(null, res)
        });
    }
});

const env = new nunjucks.Environment(new AsyncLoader('templates'));

env.render('index.html', (err, res) => {
    if (err) {
        console.error(err);
    } else {
        console.log('result:', res);
    }
});

render result:

<html>
<head>
    <title></title>
</head>
<body>

</body>
</html>

{% include %} didn't work!!! Nunjucks does not support asynchronous loader?

almightyju commented 7 years ago

I just ran into this issue when using nunjucks with adonisjs, a nastyish work around I found was to: {% include 'homePage.html' if homePage %}

Edit: i was getting myself confused at my own code and this didn't actually work, at all :(

almightyju commented 7 years ago

So I've properly fixed it now, tho I'm not 100% it's bomb proof yet, see my comment on issue #838

davethegr8 commented 6 years ago

This also occurs in v3.1.3 while inside loops: https://github.com/pkolt/express-nunjucks/issues/7#issuecomment-423000569