express-nunjucks icon indicating copy to clipboard operation
express-nunjucks copied to clipboard

"include" stops rendering in conditional

Open andersonba opened this issue 8 years ago • 4 comments

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 %}

andersonba avatar Dec 04 '16 16:12 andersonba

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.

Richie765 avatar Dec 08 '16 22:12 Richie765

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

pkolt avatar Dec 09 '16 18:12 pkolt

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.

davethegr8 avatar Sep 20 '18 00:09 davethegr8

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>

gijswijs avatar Jun 25 '20 06:06 gijswijs