express-nunjucks
express-nunjucks copied to clipboard
"include" stops rendering in conditional
Any import inside the "conditions" stops the template rendering. See below, anything is printed.
{% if enabledNewFooter %}
{% include "new_footer.html" %}
{% else %}
{% include "footer.html" %}
{% endif %}
It happens in both blocks (if
/ else
), anything is rendered.
I'm using the following way temporarily:
{% set templateFile = 'a.html' if condition else 'b.html' %}
{% include "directory/" + templateFile %}
I too was trying to include a file in many different ways and all of them failed. For instance:
{% set standardModal %}
{% include 'standardModalData.html' %}
{% endset %}
Only an include outside any block seems to work.
It seems that this is a bug of nunjucks.
To solve you can use the synchronous loader templates - nunjucks.FileSystemLoader
.
const express = require('express');
const expressNunjucks = require('express-nunjucks');
const app = express();
app.set('views', __dirname + '/templates');
const njk = expressNunjucks(app, {
loader: nunjucks.FileSystemLoader
});
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000);
This also seems to happen while inside loops.
before {% include "partials/hello-world.html" %} after
{% set items = [1, 2, 3] %}
{% for i in items %}
- {{ i }} before {% include "partials/hello-world.html" %} after
{% endfor %}
Output:
before Hello World after
- 1 before
- 2 before
- 3 before
Interestingly, besides using the FileSystemLoader, setting noCache: true
in the configure also works around this issue.
You can not use includes inside for-loops if you use async loaders. There are two alternative tags called asyncEach and asyncAll that work like the for-loop but allow for async loaders. See the documentation here: https://mozilla.github.io/nunjucks/templating.html#asynceach
Be aware that macro's don't allow for any async stuff happening inside the macro. So if you use async loaders, includes aren't an option to use inside macro's. A dirty workaround for that is to have the include before the macro call. Example:
<div>
{% include "partials/icons/" + platform + ".svg" %}
{{ icon.icon(platform) }}
</div>