Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

eleventy - Conditional not working in Nunjucks macro

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?

question from:https://stackoverflow.com/questions/65884563/conditional-not-working-in-nunjucks-macro

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...