如何在 CSS 文件中使用 Flask url_for?

The*_*ool 10 html css jinja2 flask

我正在将 Flask 与 HTML 和 CSS 结合使用。当这可能时:

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

我必须在这里写什么来处理相同的图像?

.bgimg-1 {
   background-image: url('https://i.ytimg.com/vi/J9QOB6hSI-c/maxresdefault.jpg');
   min-height: 100%; }
Run Code Online (Sandbox Code Playgroud)

解决方案应与此类似:

.bgimg-1 {
   background-image: url('{{ url_for('static', filename='images/planets.jpeg' ) }}');
   min-height: 100%; }
Run Code Online (Sandbox Code Playgroud)

谢谢你。

Gre*_* Li 14

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;
Run Code Online (Sandbox Code Playgroud)

Method 2

Put your background line into the template:

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

Method 3

Define a CSS variable in your template:

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

Then use it in your CSS file:

background: url("var(--background-url)") no-repeat 0px 0px;
Run Code Online (Sandbox Code Playgroud)