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.
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.
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.
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.
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:
Use correct relative path in your CSS file:
background: url("/static/images/bg.jpg") no-repeat 0px 0px;
Put your background
line into the template:
<style>
background: url("{{ url_for('static',filename='images/bg.jpg') }}") no-repeat 0px 0px;
</style>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With