【问题标题】:How to use macros in a included file如何在包含的文件中使用宏
【发布时间】:2013-09-25 10:21:37
【问题描述】:

view.jinja

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

defaultlayout.jinja

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

但我无法在 details.jinja 中使用宏 html 而不重新包含它

【问题讨论】:

  • 不记得这是否适用于宏,但试试include('details.jinja') with context

标签: flask jinja2


【解决方案1】:

丹尼尔的回答对我没有帮助。我必须通过以下方式导入

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

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

{{ show_post(post) }}

这里的post 是从flask render_template 发送到模板的字典。
macro file 文件看起来像这样:
post_entity.html

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

【讨论】:

  • 谢谢,不能多次投票,否则我会的。如果有人指出为什么添加 with context 会修复它,那会很好 - 以及为什么你应该得到一个错误忽略它......
【解决方案2】:

从您的示例看来,您好像在尝试导入 macros.jinja,并使用 that 作为名为 html 的宏。这样不行。

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

macros.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(...)

您需要在 macros.jinja 中定义一个名为 html 的宏,将 macros.jinja 导入为 macros,然后使用 macros.html(...) 调用它。

这有意义吗?

【讨论】:

  • UndefinedError: 'macros' is undefined
  • 必须引用:import "macros.jinja" as macros
猜你喜欢
  • 2015-03-26
  • 2014-05-04
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多