我通过 sphinx 使用 jinja2。在我的基本模板中(layout.html 我有一些宏
{%- macro post_meta(metadata) -%}
<div class="postmeta">
{{ author(metadata.author) }}
</div>
{%- endmacro -%}
我在 theme2 中使用 {%- extends "theme1/layout.html"-%}
如何在 theme2 中重新定义 post_meta
?简单地将 post_meta
的新定义放入 theme2 是行不通的。
顺便问一下,我如何使用 python 内置函数:
{{ type(metadata) }}
最佳答案
问题 1:您必须创建一个 block 以使用基本模板中的宏覆盖该 block 。这是 child 的密码。使用 use_child = False :将使用基本模板中的宏
{% block pm_mac %}
{% if use_child %}
{%- macro post_meta(metadata) -%}
.....
{%- endmacro -%}
{% else %}
{{ super() }}
{% endif %}
{% endblock %}
问题 2:您必须注册一个全局 Python 函数才能使用类型:
def py_to_upper(a):
return a.upper()
env.globals['to_upper'] = py_to_upper # register the global python function
and in the Jinja template :
{{ to_upper("lowercase") }}
关于python - 如何在jinja2中重新定义宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13820864/