Flask模板无法加载css

时间:2015-05-12 09:36:08

标签: python css flask jinja2

我按照本教程开发了带有http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates

的模板

我的文件树是下一个:

/static
   /js
        bootstrap.min.js
        jquery_1.11.3.js
   /css
        bootstrap.min.css
   /images
/templates
        index.html
/python_venv
server.py

server.py代码:

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

index.html代码中的css链接如下:

      <script src="/static/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="/static/css/bootstrap.min.css"/>
      <script src="/static/js/jquery_1.11.3.js"></script>

nginx config:

      location /subdomain/{
      root        /apps/subdomain/static;
      uwsgi_pass  unix:///tmp/subdomain.sock;
      include     uwsgi_params;
      }

当我在Chrome上查看时,索引没有加载CSS文件。我使用Developer's工具检查了网络,错误是404。 我尝试了类似的代码,我在这个未解决的问题上看到了没有成功的代码 Inline CSS background:url() not working in Jinja2 template

对此有何帮助?

2 个答案:

答案 0 :(得分:1)

问题在于服务器。

我必须为flask模板提供静态文件夹才能加载css。

我在nginx配置文件中编写了下一个:

    location /subdomain/static)/  {
       root    /opt/apps/content_folder/static;
    }

我不使用url_for()函数将资源的URL写为:

    static/css/my_css_template.css

最后检查文件中的@ app.route(),使模板呈现正确,然后烧瓶模板可以访问css,images和js。

答案 1 :(得分:0)

如果您将静态文件直接放在/ static文件夹下,这应该可以正常工作

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">

如果您不想这样,请按照此问题批准的答案中的说明进行操作,

Link to Flask static files with url_for