Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Flask url_for in a CSS file?

I'm using Flask with HTML and CSS. When this is possible:

<img src="{{ url_for('static', filename='images/planets.jpeg' ) }}">

What do I have to write here to address the same image?

.bgimg-1 { background-image: url('https://i.ytimg.com/vi/J9QOB6hSI-c/maxresdefault.jpg'); }

The solution should look similar to this:

.bgimg-1 { background-image: url('{{ url_for('static', filename='images/planets.jpeg' ) }}'); }

Thank you.

like image 379
The Fool Avatar asked Jun 26 '18 14:06

The Fool


People also ask

Does Flask work with CSS?

CSS stylesheets are considered static files. There is no interaction with their code, like there is with HTML templates. Therefore, flask has reserved a separate folder where you should put static files such as CSS, Javascript, images or other files. That folder should be created by you and should be named static.

What does Flask's url_for () do?

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for , if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Can you use HTML and CSS with Flask?

Website templates and web templates all mean the same thing. For HTML templates, they are built using HTML (or XHTML) and usually consist of CSS and JavaScript code. To create HTML webpages on the go, Flask supports HTML templating using Jinja2.


1 Answers

You can't use Jinja directly in the CSS file since you normally don't render it as a template, but there is 3 alternate way to achieve your need:

Method 1

Use correct relative path in your CSS file:

background: url("/static/images/bg.jpg") no-repeat 0px 0px;

Method 2

Put your background line into the template:

<style>
    background: url("{{ url_for('static',filename='images/bg.jpg') }}") no-repeat 0px 0px;
</style>

Method 3

Define a CSS variable in your template:

<style>
    :root {
        --background-url: {{ url_for('static', filename='images/bg.jpg') }}
    }
</style>

Then use it in your CSS file:

background: url("var(--background-url)") no-repeat 0px 0px;
like image 176
Grey Li Avatar answered Oct 26 '22 01:10

Grey Li