代码之家  ›  专栏  ›  技术社区  ›  aWebDeveloper

如何在包含的文件中使用宏

  •  20
  • aWebDeveloper  · 技术社区  · 11 年前

    视图.jinja

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

    默认布局.jinja

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

    但我不能使用宏 html格式 在details.jinja中,但不重新包含

    2 回复  |  直到 11 年前
        1
  •  25
  •   Nam G VU    3 年前

    丹尼尔的回答对我没有帮助。我不得不用以下方式导入

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

    在这里 post_entity.html 是包含宏的文件 show_post 方法
    然后使用以下方式:

    {{ show_post(post) }}
    

    在这里 post 是从发送到模板的词典 瓶子 render_template .
    macro file 文件看起来像这样:
    发布_实体.html

    {% macro show_post(post) %}
        {{ post.photo_url }}
        {{ post.caption }}
    {% endmacro %}
    
        2
  •  15
  •   pdoherty926    5 年前

    从你的例子来看,你似乎正在尝试导入 macros.jinja ,和使用 那个 作为一个名为 html 。它不是那样工作的。

    宏是在一个jinja文件中定义的,在那里有名称。

    宏观.jinja:

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

    然后可以使用import标记导入整个文件:

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

    那么,在您当前的命名空间中,您将拥有 macros ,指向macros.jinja文件。要使用 dostuff 宏,您必须调用 macros.dostuff(...) .

    您需要定义一个名为 html格式 在macros.jinja内部,将macros.jin导入为 ,然后用调用 macros.html(...) .

    这有道理吗?

    推荐文章