Reputation: 40084
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.
Upvotes: 2
Views: 2193
Reputation: 5225
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) }}
Upvotes: 6
Reputation: 100
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.
Upvotes: 0