Jinja2中url_for()内的标签块 [英] Block tag inside url_for() in Jinja2

查看:230
本文介绍了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>

到目前为止,太好了.但是我想在filename参数中放置一个块,以便我可以重用代码并仅覆盖图像的名称.这就是我正在尝试的:

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/

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模板中,并导入每页.

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()内的标签块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆