无法使用jinja更改内联css

时间:2016-04-18 10:42:59

标签: python html css flask jinja2

我必须根据从数据库中获取的输入更改下面的jumbotron的背景图像。 这是代码:

housekeeping.html

<div class="jumbotron" style="background-image:url('{%block wallpaper%}{%endblock%}');padding-left:5%;width:100%;background-size: 100%; background-repeat: no-repeat;">

profile.html

{%extends 'housekeeping.html'%}
...
...
{%block wallpaper%}{{wallpaper}}{%endblock%}

app.py

@app.route('/name/<b64>')
def profile_for_song(b64):
    ... 
    ... #retrives the value of `wallpaper` form a row in the database.
    ...
    wallpaper = '/static/wallpaper.jpg' #dummy value. 
    return render_template('profile.html', wallpaper=wallpaper)

但它不起作用,因为background-image:url('')的值仍然为空。
是不是可以用jinja块改变css?

PS:我试过url_for,但仍然没有。

1 个答案:

答案 0 :(得分:1)

在profile.html中观看壁纸块中whitespace控件的使用。

<强> app.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    wallpaper = '/static/wallpaper.jpg'
    return render_template('profile.html', wallpaper=wallpaper)


if __name__ == '__main__':
    app.run()

<强> housekeeping.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css">
</head>
<body>

    <div class="jumbotron" style="background-image:url('{% block wallpaper%}{% endblock %}');padding-left:5%;width:100%;background-size: 100%; background-repeat: no-repeat;">
    </div>

</body>
</html>

<强> profile.html

{%extends 'housekeeping.html'%}

{% block wallpaper -%}
    {{ wallpaper }}
{%- endblock %}

示例输出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css">
</head>
<body>

    <div class="jumbotron" style="background-image:url('/static/wallpaper.jpg');padding-left:5%;width:100%;background-size: 100%; background-repeat: no-repeat;">
    </div>

</body>
</html>