23

view.jinja

{% extends "layout/defaultlayout.jinja" %}
{% include('details.jinja') %}

defaultlayout.jinja

{% import 'elements/macros.jinja' as html %}

But i am not able to use the macro html in details.jinja without reincluding it

1
  • 1
    Do not really remember if this applies to macros, but try include('details.jinja') with context
    – Tigra
    Sep 25, 2013 at 21:47

2 Answers 2

31

Daniel's answer didn't help me. I had to import the following way

{% from "post_entity.html" import show_post with context %}

Here post_entity.html was file containing macro with show_post method
And then used following way:

{{ show_post(post) }}

Here post is a dictionary sent to template from flask render_template.
And the macro file file looked something like this:
post_entity.html

{% macro show_post(post) %}
    {{ post.photo_url }}
    {{ post.caption }}
{% endmacro %}
1
  • 3
    Thanks, can't upvote more than once otherwise I would. It would be nice having someone pointing out why adding with context fixes it — and also why you should get an error omitting it...
    – neurino
    Dec 20, 2018 at 8:11
17

It looks, from your examples, as if you're trying to import macros.jinja, and use that as a macro called html. It doesn't work like that.

Macros are defined within a jinja file, with names there.

macros.jinja:

{% macro dostuff(x,y,z) %}
    <a href="{{ x }}" title="{{y}}">{{z}}</a>
{% endmacro %}

and you can then import whole files with the import tag:

{% import "macros.jinja" as macros %}

so then, in your current namespace, you will have macros, which points to the macros.jinja file. To use the dostuff macro, you have to call macros.dostuff(...).

You need do define a macro called html inside macros.jinja, import macros.jinja as macros, and then call it with macros.html(...).

Does that make sense?

2
  • 1
    UndefinedError: 'macros' is undefined
    – Sparr
    Jan 22, 2016 at 0:35
  • 4
    Quotes is a must: import "macros.jinja" as macros Mar 10, 2018 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.