abhijeet kaurav
abhijeet kaurav

Reputation: 105

If we have multiple macros in single jinja template. How to render a particular macro in it in python

Ex: name = aa.py.jinja2

{% macro Macro1() -%}
...
{%- endmacro %}

{% macro Macro2() -%}
...
{%-endmacro %}

Rendering in python

loader = PackageLoader(__name__, "")
env = Environment(loader=loader)
template = env.get_template("aa.jnja2")

aa = template.render("Macro1")

How to render particular macro..Otherwise have to create separate template for each macro

Upvotes: 1

Views: 1162

Answers (2)

qwwerty
qwwerty

Reputation: 11

You can copy approach used by Flask in get_template_attribute
https://github.com/pallets/flask/blob/main/src/flask/helpers.py#L315

Example:
macros.j2 as Jinja template file. It can contain multiple macros, so you can have them all in one file.

{% macro console(content) %}
    {% if content %}
        <div class="console">{{ content|escape }}</div>
    {% endif %}
{% endmacro %}

Loading the macro and using it as a function. All you have to specify is which getattrib you want from your macro file. Attributes correspond to the macro names, ie console in this snippet.

from jinja2 import Environment, FileSystemLoader

j2env = Environment(loader=FileSystemLoader("."))
macro = getattr(j2env.get_template("macros.j2").module, "console")

text = macro("I'm a <html> tag wrapped in a console div block")
print(text)

Result:

<div class="console">I&#39;m a &lt;html&gt; tag wrapped in a console div block</div>

Upvotes: 0

blhsing
blhsing

Reputation: 106883

Macros are comparable with functions and are meant to be called. You can import aa.jinja2 first and then call its Macro1 function:

aa = env.from_string('{% import 'aa.jinja2' as aa %}{{ aa.Macro1() }}').render()

Upvotes: 1

Related Questions