如何使用Jinja模板动态添加背景图像的url ?



所以我从端点获取数据的迷你博客和JSON bin中的每个帖子都有一个图像属性,其中是一个相应的链接到Unsplash的背景图像。如:

[
{
"id": 1,
"title": "The Life of Cactus",
"body": "Nori grape silver...",
"date": "31-08-2022",
"author": "Bakes Parker",
"image": "https://images.unsplash.com/photo-1544674644-c8c919e3cfbf?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=755&q=80"
},

在我的Flask应用程序中,我得到各自的帖子,用Flask渲染它们,用Jinja使用动态值。下面是获取帖子的函数:

@app.route("/post<int:num>")
def return_post(num):
API_ENDPOINT = "https://api.npoint.io/xxx"
blog_stories = requests.get(API_ENDPOINT).json()
requested_story = None
for blog_post in blog_stories:
if blog_post['id'] == num:
requested_story = blog_post
return render_template("post.html", requested_post=requested_story)

内的post.html,我试着用这行

来制作各自帖子的背景。

<style>
header {
background-image: url("{{requested_post['image']}}");
}
</style>

但是它没有显示,因为它显示的是默认的#cccc background-img color。

我也尝试使它内联,但这是不可能的,因为CSS花括号的限制。如:

<header class="masthead" style="background-image:{{requested_post['image']}} ;">

我不能做以上。

所以我发现来自端点的图像实际上是渲染的,但是它们被样式表中的属性覆盖了,这很奇怪,因为我在样式标签中定义了样式。开发人员工具显示图像在那里

给您带来的不便我深表歉意。

一切正常。尝试从flask导入current_app,然后打印出json进行调试。也许你没有得到你想要的数据。

from flask import current_app
@app.route("/post<int:num>")
def return_post(num):
API_ENDPOINT = "https://api.npoint.io/xxx"
blog_stories = requests.get(API_ENDPOINT).json()
for requested_post in blog_stories:
if requested_post.get('id') == num:
current_app.logger.debug(requested_post)
return render_template("post.html", requested_post=requested_post)
return render_template("error.html")

我建议你考虑重定向到一个错误的模板或路由。

你可以张贴你完整的模板吗?那里可能有线索。