Nunjucks: Include template inside a conditional

Created on 15 Jan 2017  路  4Comments  路  Source: mozilla/nunjucks

Hey everyone!

I don't know why but when I include a file within a conditional it will not display it.

Example:

{# currentUser = null or an object #}
{% if currentUser %}
  {% include 'frontend.layout.partials.user' %}

  <div class="nav-bar-separator"></div>

  {% include 'frontend.layout.partials.userAction' %}
{% else %}
  {% include 'frontend.layout.partials.login' %}
{% endif %}

The second weird thing is if I include it twice (once outside the conditional) it will display it twice.

{# currentUser = null or an object #}
{% if currentUser %}
  {% include 'frontend.layout.partials.user' %}

  <div class="nav-bar-separator"></div>

  {% include 'frontend.layout.partials.userAction' %}
{% else %}
  {% include 'frontend.layout.partials.login' %}
{% endif %}

{% include 'frontend.layout.partials.login' %}

Any idea how I can fix this?

Note: I'm using AdonisJs Framework that use nunjucks for the View Layer. [[code](https://github.com/adonisjs/adonis-framework/tree/develop/src/View)]


Related issue:

Most helpful comment

{% ifAsync currentUser %}

Seems to work!

All 4 comments

Any news?

ping @jlongster @carljm

{% ifAsync currentUser %}

Seems to work!

Why was this issue closed? Using "IfAsync" instead "If" is cleary not a fix. For example, there's no async analog for "while".

I have issue with rendering such template:
[% for dItem in data %] [% include "blocks/tags.html" %] [% endfor %]

I'd generally recommend not to use include at all and instead rely solely on macros.

That way you will never include/import anything conditionally, thus will never get that issue:

{% from 'blocks/Tags.nj' import Tags %}

{% for dItem in data %}{{ Tags() }}{% endfor %}

Performance wise it will be better because you will not include anything in a loop. Import will occur only once, while in the loop only invocation will be used.

And in terms of architecture, it is a better solution too.

Was this page helpful?
0 / 5 - 0 ratings