Jinja2 中 url_for() 中的块标记

2023-09-02Python开发问题
31

本文介绍了Jinja2 中 url_for() 中的块标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 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>

这篇关于Jinja2 中 url_for() 中的块标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10