首页 > 解决方案 > 烧瓶,url_for()没有链接静态文件

问题描述

我无法链接我的静态“css”文件。当我运行代码时,我只得到我的基本 html 而不是 css。当我使用 html 元素时,我的所有 css 代码都可以正常工作。这是我的代码:

h1 {
  padding: 60px;
  text-align: center;
  background: #1abc9c;
  color: white;
  font-size: 30px;
}

.header {
  padding: 60px;
  text-align: center;
  background: #1abc9c;
  color: white;
  font-size: 30px;
}

.sidebar {
  height: 200px;
  width: 150px;
  position: sticky;
  top: 0px;
  float: right;
  margin-top: 100px;
  padding-top: 40px;
  background-color: lightblue;
}

.sidebar div {
  padding: 8px;
  font-size: 24px;
  display: block;
}

.body-text {
  margin-right: 150px;
  font-size: 18px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="UTF-8">
  <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>


<body>
  <h1>Header</h1>


  <div class="sidebar">
    <div>Menu Item 1</div>
    <div>Menu Item 2</div>
    <div>Menu Item 3</div>
  </div>

  <div class="body-text">
    <!-- body content -->
  </div>
</body>

</html>

这是我的python代码,以防万一导致问题:

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)

app.config['ENV'] = 'development'
app.config['DEBUG'] = True
app.config['TESTING'] = True

app.static_folder = 'static'

@app.route('/')
def index():
    return render_template('base.html')

@app.route('/<name>')
def user(name):
    return f"Hello {name}!"

@app.route('/admin')
def admin():
    return redirect(url_for('index', name='Admin'))

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

谢谢你的帮助。对不起,如果代码很乱,我是菜鸟:)。

标签: pythonhtmlcssflask

解决方案


除了上面给出的答案之外,如果您的浏览器已经缓存了 CSS 文件,有时也会发生这种情况。Ctrl+f5每次在文件中添加新代码时,您都可以强制浏览器刷新键盘上的内容style.css


推荐阅读