bryhoyt
bryhoyt

Reputation: 273

Import macros from a Jinja template without executing the template content

I would like to import a Jinja template that also has top-level content, but without executing the content itself. For example:

template_with_macros.html:

{% macro link(text, url) %}
  <a href='{{ url }}'>{{ text }}</a>
{% endmacro %}
{% for text, url in {'Google': 'http://google.com', 'Stack Overflow': 'http://stackoverflow.com'}.items() %}
  {{ link(text, url) }}
{% endfor %}

template_that_uses_macros.html:

{% import "template_with_macros.html" as macros %}
{{ macros.link("Homepage", "/") }}

When you import a Jinja template, the template's content is not included, but it is still executed, which means any non-existent variables will cause errors, among other bad things that happen when you execute unwanted code.

Is there a way to import a Jinja template without executing its content?

I want to do this, rather than factor the macros into another file altogether, because it would be a tidier way to organise the template code in my application.

Upvotes: 1

Views: 1761

Answers (1)

davidism
davidism

Reputation: 127310

No, there is no way to do this. A Jinja template compiles to a Python module. Top level code is executed when a module is imported. The same applies to templates.

Upvotes: 2

Related Questions