简体   繁体   中英

Call nunjucks template macro using variable name

Given a macro:

{% macro foo() %}
{% endmacro %}

Is there a way to call it using a variable name:

{% set fn = 'foo' %}
... call macro using 'fn'

Alternatively how can I call a macro from a custom tag? I have created a tag that can accept these variables but not sure how to insert a macro from there.

The simple way to do this is use current context

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

In template

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

{% set fn = 'foo' %}
{{ getContext(fn)(arg1, arg2) }}

I think I have an answer to this. I've been working on this very problem, and have it sort-of working. Maybe you can take what I propose here and expand on it.

The basic premise is to hand-off the rendering to another macro, like so:

{% macro eval(fn,data) %}
  {{ fn(data) }}
{% endmacro %}

Then:

{% set fn = foo %}
{% set data = { this: that } %}
{{ eval(fn,data) }}

What I haven't figured out yet is how to evaluate a variable passed into the template from an external source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM