Flask Web App的CSS问题 [英] CSS Problems with Flask Web App

查看:167
本文介绍了Flask Web App的CSS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我所有模板中的链接。

我无法获得CSS正确输出 - 我的网页都是无格式的。我做错了什么?

 < link type =text / css =stylesheethref =/ stylesheets /style.css\"/> 

有没有什么特别的事情要和Flask打交道呢?



我一直在尝试和改变大约半个小时的东西,但似乎无法得到正确的。



总结一下:你如何使用Flask做CSS?我必须有什么特殊的Python代码吗?

不需要对Flask做任何特殊的事情来让CSS工作。也许你把 style.css 放在 flask_project / stylesheets / 中?除非正确配置,否则这些目录将不会被您的应用程序提供。请查看静态文件部分。 /flask.pocoo.org/docs/quickstart/rel =noreferrer> Flask Quickstart 了解更多信息。但是,总之,这是你想要做的:


  1. 将需要的静态文件移动到 project_root /静态/ 。假设您将 stylesheets / style.css 移至 project_root / static / stylesheets / style.css


  2. 更改

     < link ... href =/ stylesheets / style.css/> 

     < link ... href ={{url_for('static',filename ='stylesheets / style.css')}}/> 

    这告诉模板解析器(Jinja2)告诉Flask在你的工程目录中找到配置好的静态目录(默认情况下, static / )并返回该文件的路径。
    $ b


    • 如果你真的想要,你可以设置路径为 /static/stylesheets/style.css 。但是你真的不应该这么做 - 使用 url_for 可以让你切换你的静态目录,还有其他的好处。


然后,@RachelSanders在她的回答中说:


在生产环境中,您最好通过apache或nginx来提供静态文件,但这对于开发者来说已经足够了。


I can't get the CSS to output correctly - my webpages are all unstyled.

This is my link in all my templates. What am I doing wrong?

<link type="text/css" rel="stylesheet" href="/stylesheets/style.css"/>

Is there anything special that I have to do with Flask to get it to work?

I've been trying and changing things for about half an hour but can't seem to get it right.

To sum it up: How do you do CSS with Flask - do I have to have any special python code?

解决方案

You shouldn't need to do anything special with Flask to get CSS to work. Maybe you're putting style.css in flask_project/stylesheets/? Unless properly configured, such directories won't be served by your application. Check out the Static Files section of the Flask Quickstart for some more information on this. But, in summary, this is what you'd want to do:

  1. Move static files you need to project_root/static/. Let's assume that you moved stylesheets/style.css into project_root/static/stylesheets/style.css.

  2. Change

    <link ... href="/stylesheets/style.css" />
    

    to

    <link ... href="{{ url_for('static', filename='stylesheets/style.css') }}" />
    

    This tells the template parser (Jinja2) to tell Flask to find the configured static directory in your project directory (by default, static/) and return the path of the file.

    • If you really wanted to, you could just set the path as /static/stylesheets/style.css. But you really shouldn't do that - using url_for allows you to switch your static directory and still have things work, among other advantages.

And, as @RachelSanders said in her answer:

In a production setting, you'd ideally serve your static files via apache or nginx, but this is good enough for dev.

这篇关于Flask Web App的CSS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆