如果您将 CSS 配置为后端渲染过程的一部分,则将样式更改视为模板中的任何其他变量:
from flask import Flask, render_template_string
app = Flask(__name__)
index_page = """<html><body><h2 style="color: {{ color }}">Index page</h2></body></html>"""
@app.route('/')
def index():
with open('/path/to/file.txt') as f:
color = f.readlines()[-1]
return render_template_string(index_page, color=color)
if __name__ == '__main__':
app.run()
file.txt
例如,如果以 结尾blue
,则标题将为蓝色。red
,yellow
等也是如此。
您正在更改 CSS 值而不是表中的值这一事实对 Jinja 没有任何影响。
相反,如果您在服务器呈现页面并将其发送到客户端之后尝试更新 CSS 值,那么您需要使用 JavaScript。在您的后端,添加一个额外的视图以从服务器获取该数据:
@app.route('/lastline')
def last_line():
with open('/path/to/file.txt') as f:
color = f.readlines()[-1]
return color
使用 jQuery 从客户端访问此端点:
<script>
function updateCSS() {
$.ajax({
url: "{{ url_for('last_line') }}",
method: 'GET',
success: function(data) {
$("#baz").css("visibility", data);
}
});
}
setInterval(updateCSS, 1000);
</script>
这将每 1 秒检查一次文件并相应地更新元素的 CSS。