aWebDeveloper
aWebDeveloper

Reputation: 38432

How to use macros in a included file

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

Upvotes: 25

Views: 23942

Answers (2)

Nabin
Nabin

Reputation: 11786

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 %}

Upvotes: 35

Daniel Fairhead
Daniel Fairhead

Reputation: 1161

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?

Upvotes: 19

Related Questions