0

I am using Nunjucks (with Eleventy) and have been refactoring some navigation html to simplify things. I have replaced all the 'a' navigation tags with the macro defined below:

{% macro link(path,label,level) %}
  <!-- path = '{{ path }}/', page.url = '{{ page.url }}' -->
  <a href="{{ path }}/index.html"
     class="level_{{ level }} {{ 'current' if '{{path}}/' == page.url }}"><span>{{ label }}</span></a>
{% endmacro %}

I now find that the 'if' statement which was working fine before no longer works when it is used in the macro. Its purpose is to assign the 'current' class for the link to the page the user is currently on.

Note the comment in the macro. This is a test so I can see what the values being compared are. The odd thing is that the test indicates there's nothing wrong with the values, but the 'if' statement is still not running. For example, this is an example of what appears in the comment for the link to the current page (where the 'current' class should be assigned): `. As you can see, the two values are identical. So why is the 'if' test failing?

John Moore
  • 6,739
  • 14
  • 51
  • 67
  • 1
    I see you already found a solution, BTW the reason your original code wasn't work is that string interpolation simply doesn't exist in Nunjucks. You need to use string concatenation, as you found out. Here's an issue on that topic: https://github.com/mozilla/nunjucks/issues/899 – MoritzLost Jan 25 '21 at 16:20
  • That's not strictly true, in fact. The other parts of the markup in this worked fine. The href and class were correctly formed: ` – John Moore Jan 26 '21 at 18:00
  • 1
    Both of those examples aren't string interpolation, just outputting a variable. The difference is in whether you using double brackets to output a variable, or to form part of the string. The latter is string interpolation, which doesn't exist in Nunjucks. So this is just outputting a regular variable: `{{ path }}/index.html`, which is fine. But here you are _inside_ a string literal: `'{{path}}/'`. Since Nunjucks doesn't have string interpolation, this is just a literal string including the curly brackets and will never include the contents of the path variable. – MoritzLost Jan 27 '21 at 09:16

1 Answers1

0

OK, seems like the issue was the interpolation. It works fine when changed to this:

{% macro link(path,label,level) %}
  <a href="{{ path }}/index.html"
     class="navLink level_{{ level }} {{ 'current' if (path+"/" == page.url) }}"><span>{{ label }}</span></a>
{% endmacro %}
John Moore
  • 6,739
  • 14
  • 51
  • 67