How to use macros in the included file

view.jinja

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

defaultlayout.jinja

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

But I can not use the html macro in details.jinja without including it

+9
source share
2 answers

From your examples, it looks like you are trying to import macros.jinja and use it as a macro called html . This does not work like that.

Macros are defined in a jinja file with names there.

macros.jinja:

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

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

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

So, in your current namespace you will have macros that points to the macros.jinja file. To use the dostuff macro, you need to call macros.dostuff(...) .

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

Does this make sense?

+8
source

Daniel's answer did not help me. I had to import as follows

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

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

 {{show_post(post)}} 

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

 {% macro show_post(post) %} {{post.photo_url}} {{ post.caption }} {% endmacro %} 
+7
source

All Articles