Jinja2 中 url_for() 中的块标记

2022-01-19 00:00:00 python jinja2 frontend

问题描述

我正在使用 Jinja2 来呈现我的前端(而 python 在后端).每个页面的顶部都会有不同的图像,如下所示:

I'm using Jinja2 to render my frontend (and python is on the backend). Each page will have a different image on its top, like this:

<header>
    <img src="static/img/pic1.png">
</header>

我使用 url_for() 来获取我的静态文件夹的正确路径:

I used url_for() to get the correct path of my static folder:

<header>
    <img src="{{ url_for('static', filename='img/pic1.png') }}"> 
</header>

到目前为止,一切都很好.但是我想在文件名参数中放置一个块,这样我就可以重用代码并且只覆盖图像的名称.这就是我正在尝试的:

So far, so good. But I would like to put a block inside the filename parameter, so I can reuse the code and only overwrite the name of the image. This is what I'm trying:

<header>
    <img src="{{ url_for('static', filename='{% block img %}img/pic1.png{% endblock %}') }}">
</header>

但是不行,这是Jinja2渲染的最终代码:

But it doesn't work, this is the final code that is rendered by Jinja2:

<header>
    <img src="/static/%7B%25%20block%20img%20%25%7Dimg/pic1.png%7B%25%20endblock%20%25%7D">
</header>

如您所见,Jinja2 不将 block 标签识别为表达式,而是将其视为字符串.如果可行,我将能够仅使用此代码设置每个页面的图片:

As you can see, Jinja2 doesn't recognize the block tag as an expression and treats it as a string. If it worked, I would be able to set the picture of each page only using this code:

{% extends "base.html" %}
{% block img %}img/pic2.png{% endblock %}
...

有人可以帮忙吗?顺便说一句,这篇帖子对我没有帮助.

Could someone help, please? By the way, this post didn't help me.


解决方案

你需要一个宏来在你的模板中定义一种函数.请参阅此主题http://jinja.pocoo.org/docs/dev/templates/p>

What you need is a macro to define a kind of function in your template. See this topic in http://jinja.pocoo.org/docs/dev/templates/

{% macro header_img(name) -%}
    <img src="{{ url_for('static', filename=name) }}">
{%- endmacro %}

您可以将此宏放在 util 模板中,然后将其 import每一页.

You can put this macro in an util template and import it in each page.

使用语法:

<header>{{ header_img("your_image.jpg") }}</header>

相关文章