Skip to content Skip to sidebar Skip to footer

Jinja2 Set Background Image

I am trying to set the background image using jinja2. I have managed to serve my file from my dev server and can post the image in the document, but I want it to form a nice backg

Solution 1:

You seem to be trying to tell the front end to use application routing without passing it the right commands. I'm assuming you're using Flask. Really, there are two ways (that I can think of) to slice this bread, and it just depends on you. The first is just using standard html and not embedding python to route the app to look for the file, and looks like:

<body background="/path/to/image.jpg">

But, if you want to take advantage of the framework and the template, then you should use the built in method url_for

It looks something like this:

<body background="{{ url_for('static', filename=commPageData.background_image) }}">

'static' being the directory in the application where this image lives.

Now, I'm not sure where commPageData.background_image is coming from in your app. My code snip assumes it is being served as a value it will recognize if passed back to the logic, if that makes sense, and it needs to be where you tell the url_for method looks for it, even when dynamically generated. If you actually have a specific image you want to render as the background, it needs to be specified appropriately:

<body background="{{ url_for('static', filename='image.jpg') }}">

Of course, has been deprecated in HTML5 and may not render appropriately in many browser. It is much preferred to use CSS instead with

<body style="background:url({{'images/'+commPageData.background_image}});"> 

or put it directly in your CSS file


Post a Comment for "Jinja2 Set Background Image"