Block tag inside url_for() in Jinja2(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="c3RhdGljL2ltZy9waWMxLnBuZw==">
</header>
我使用 url_for() 来获取我的静态文件夹的正确路径:
I used url_for() to get the correct path of my static folder:
<header>
<img src="e3sgdXJsX2Zvcig="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="e3sgdXJsX2Zvcig="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="L3N0YXRpYy8lN0IlMjUlMjBibG9jayUyMGltZyUyMCUyNSU3RGltZy9waWMxLnBuZyU3QiUyNSUyMGVuZGJsb2NrJTIwJTI1JTdE">
</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="e3sgdXJsX2Zvcig="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() 中的块标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jinja2 中 url_for() 中的块标记


- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01