How to use Flask url_for in a CSS file?
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;
You are serving css statically, via /static/css/style.css
. When you do this, then Flask does not use Jinja to parse the CSS file as though it were a template.
If, however, you had a route (eg @app.route('/css/<file>')
) then you could use the render_template() method to render your CSS file as though it were a jinja template, which would then parse the jinja directives (such as {{url_for()}}
)
You can simply refer to the generated URL in your url_for
function.
As an example:
.bgimg-1 { background-image: url('/static/images/planets.jpeg'); min-height: 100%;}
Also, please note that the CSS itself can be referenced with:
<link rel="stylesheet" href="{{ url_for('static', filename='css/planets.css') }}">
UPDATE:
Alternatively, you can embed your Jinja2 in the style attribute. For example:
<body style="background-image: url({{ url_for('static', filename='images/planets.jpeg') }});"><!-- HTML TEMPLATE CODE --></body>