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.48k stars 635 forks source link

Include async templates inside an `if` #1375

Closed oscarotero closed 2 years ago

oscarotero commented 2 years ago

Hi.

I have an async filter, for example this one:

// Add the "async" filter
env.addFilter("async", (name, cb) => {
  setTimeout(() => cb(null, name.toUpperCase()), 1);
}, true);

// Render the template
env.render('page.njk', { username: "James" }, function(err, res) {
  console.log(res);
});

This filter can be used in the templates without problems:

<!-- page.njk -->

{% include "title.njk" %}
<!-- title.njk -->

<h1>Hello {{ username | async }}</h1>

This outputs <h1>Hello JAMES</h1>


But if I import the template inside an if, it outputs an empty string

<!-- page.njk -->

{% if true %}
    {% include "title.njk" %}
{% endif %}

This outputs an empty string

Is there any way to import an async template condicionally? I see there's an asyncEach and asyncAll tags but I didn't find an asyncIf.

oscarotero commented 2 years ago

@ManishOffi I can't. I don't have permissions in this repository to do that.

fdintino commented 2 years ago

It looks like it may be missing from the documentation, but there is an ifAsync tag that might be what you're looking for

oscarotero commented 2 years ago

@fdintino ok, thanks for your help. Indeed, this code works fine:

{% ifAsync true %}
    {% include "title.njk" %}
{% endif %}