用 Jinja2 中的模板输出替换字符串
Replace string with template output in Jinja2
在 Pelican 中,页面内容作为 page.content
传递给 Jinja2 模板。假设 page.content
包含一个字符串 {REPLACEME}
。我现在如何用某些模板逻辑的结果替换此字符串 {REPLACEME}
,比如
{% for pub in publications %}
{% set key, year, text, bibtex, doi, url, pdf, slides, poster = pub %}
{% if "%s"|format(year) == "%s"|format(yr) %}
<li id="{{ key }}">{{ text }}</li>
{% endif %}
{% endfor %}
我的想法是,我想使用模板逻辑来呈现项目列表,但仍然能够决定该列表应该出现在 page.content
.
中的什么位置
我知道 Jinja2 中有一个 replace()
filter,但我不知道如何让 new
参数包含上面的模板输出。
原来 Jinja2 中有 宏。
{% macro bibtex_rendered() -%}
{% for pub in publications %}
{% set key, year, text, bibtex, doi, url, pdf, slides, poster = pub %}
{% if "%s"|format(year) == "%s"|format(yr) %}
<li id="{{ key }}">{{ text }}</li>
{% endif %}
{% endfor %}
{%- endmacro %}
然后我可以在对 replace
:
的调用中使用定义的宏
{{ page.content | replace("{PUBLICATIONS}", bibtex_rendered()) }}
在 Pelican 中,页面内容作为 page.content
传递给 Jinja2 模板。假设 page.content
包含一个字符串 {REPLACEME}
。我现在如何用某些模板逻辑的结果替换此字符串 {REPLACEME}
,比如
{% for pub in publications %}
{% set key, year, text, bibtex, doi, url, pdf, slides, poster = pub %}
{% if "%s"|format(year) == "%s"|format(yr) %}
<li id="{{ key }}">{{ text }}</li>
{% endif %}
{% endfor %}
我的想法是,我想使用模板逻辑来呈现项目列表,但仍然能够决定该列表应该出现在 page.content
.
我知道 Jinja2 中有一个 replace()
filter,但我不知道如何让 new
参数包含上面的模板输出。
原来 Jinja2 中有 宏。
{% macro bibtex_rendered() -%}
{% for pub in publications %}
{% set key, year, text, bibtex, doi, url, pdf, slides, poster = pub %}
{% if "%s"|format(year) == "%s"|format(yr) %}
<li id="{{ key }}">{{ text }}</li>
{% endif %}
{% endfor %}
{%- endmacro %}
然后我可以在对 replace
:
{{ page.content | replace("{PUBLICATIONS}", bibtex_rendered()) }}