Nunjucks 宏中的 If 语句不起作用

If Statement in Nunjucks Macro Not working

我是 Nunjucks 的新手。到目前为止我很喜欢它,但是 运行 遇到了问题。

我刚刚制作了一个可以输出标题和描述的宏。我在我的宏中也有 if 语句来显示特定的 div "if" 我在某个页面上。

我的问题是我的 "if statement" 根本无法正常工作。不能在这样的宏中执行 "if statement" 吗?我知道 if 语句工作正常。如果我将 .njk 模板包含在内,它就会起作用。这是一个例子:

{% macro titleInfo(title, description) %}

<div class="header-title text-white">
  <div class="container">
    <div class="row align-items-center">
      <div class="col-sm-12 col-lg-9">
        <h1>
          {{title}}
        </h1>
        <p>
          <small>
            {{description | safe}}
          </small>
        </p>
      </div> <!-- /.col -->
      {% if active_page == 'check' %} {# this isn't working right now #}
        <div class="col-sm-12 col-lg-3 text-lg-right frames-in-stock">
          <p>
            <strong>000</strong> of <strong>000</strong>
          </p>
        </div> <!-- /.col -->
      {% endif %}
    </div> <!-- /.row -->
  </div> <!-- /.container -->
</div> <!-- /.header-title -->

{% endmacro %}

我包括宏并在我的页面上实现它,如下所示:

 {% extends "layout.njk" %}
 {% set active_page = "check" %}
 {% import "../templates/components/header-title.njk" as title %}
 {% block content %}

   {% include "components/header.njk" %}

   {# {% include "components/header-title.njk" %} #}

   {{
     title.titleInfo (
       'Your Inventory',
       'Please check all that apply.'
     )
   }}

  {% include "components/main-nav.njk" %}

{% endblock %}

宏中不能有if语句吗?如果可能的话,任何关于我做错的方向都会很棒!

宏在单独的文件中定义时无法访问全局范围。您必须将 active 作为变量传递给宏。

{% macro titleInfo(title, description, active) %} ...


另一种方法是使用自定义加载器在 运行 时间将宏替换为主渲染页面。

....
// rendered template
{% set active = true %}
{% enable SOMEMACRO %}
...
// somemacro.njk
{% macro SOMEMACRO %}
...
{% endmacro %}
...


// the custom loader implementation to support {% enable regexp-macro-name %}

let macros = fs.readdirSync('templates/macros')
    .reduce(function (res, f) { 
         res[f] = fs.readFileSync(`templates/macros/${f}`, 'utf8'); 
         return res;
    }, {});

let CustomLoader = nunjucks.FileSystemLoader.extend({
    getSource: function(name) {
        let result = nunjucks.FileSystemLoader.prototype.getSource.call(this, name);

        if (!result) 
            return null;

        result.src = result.src.replace(/{%\senable\s(\S+)\s%}/g, 
            function(str, match, offset, s){
                return Object.keys(macros)
                    .filter((key) => (new RegExp(match)).test(key))
                    .map((key) => macros[key] || '')
                    .join('\n');    
            }
        );

        return result;
    }
}); 

let env = new nunjucks.Environment(new CustomLoader(['templates/']), {autoescape: true});
env.express(app);