使用变量名调用 nunjucks 模板宏

cyb*_*bat 2 javascript nunjucks

给定一个宏:

{% macro foo() %}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用变量名来调用它:

{% set fn = 'foo' %}
... call macro using 'fn'
Run Code Online (Sandbox Code Playgroud)

或者,如何从自定义标签调用宏?我创建了一个可以接受这些变量的标签,但不确定如何从那里插入宏。

Aik*_*wai 6

执行此操作的简单方法是使用当前context

let env = nunjucks.configure([
...
env.addGlobal('getContext', function(name) { 
    return (name) ? this.ctx[name] : this.ctx;
})
Run Code Online (Sandbox Code Playgroud)

在模板中

{% macro foo (arg1, arg2) %}
    {{arg1}}{{arg2}}
{% endmacro %}

{% set fn = 'foo' %}
{{ getContext(fn)(arg1, arg2) }}
Run Code Online (Sandbox Code Playgroud)