Home > Software design >  how can I add a url for a background image dynamically with Jinja templating?
how can I add a url for a background image dynamically with Jinja templating?

Time:07-06

so I'm fetching data for a mini-blog from an endpoint and each post in the JSON bin has an image property and in it is a corresponding link to a background image from Unsplash. As in:

[
    {
        "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"
    },

Inside my Flask application, I get respective posts and render them with Flask and use dynamic values with Jinja. Here's the function that gets the posts:

@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)

Inside post.html, I try to make the background of the respective post with this line

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

but it doesn't show as it shows the default #cccc background-img color.

I also try to make it inline but it's not possible because of CSS curly brace restrains. As in:

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

I can't do the above.

CodePudding user response:

Nothing jumps out as wrong. Try importing current_app from flask, then printing out your json to debug. Perhaps you are not getting the data you are expecting.

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")

I suggest you think about redirecting to an error template or route here.

Can you post your complete template? There may be clues there.

CodePudding user response:

So I found out that the images from the endpoint were actually rendering but they were overridden by properties from the stylesheet which is quite odd because, I defined the style inside the style tag. Developer Tools shows that the image is there

Sorry for any inconvenience.

  • Related