Flask Web 应用程序的 CSS 问题 [英] CSS Problems with Flask Web App

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

问题描述

我无法让 CSS 正确输出 - 我的网页都没有样式.

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"/>

我需要用 Flask 做些什么才能让它工作吗?

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.

总结一下:你是如何用 Flask 做 CSS 的——我需要有任何特殊的 Python 代码吗?

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

推荐答案

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

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. 将您需要的静态文件移动到project_root/static/.假设您将 stylesheets/style.css 移动到 project_root/static/stylesheets/style.css.

  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.

改变

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

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

这告诉模板解析器(Jinja2)告诉 Flask 在你的项目目录中找到配置好的静态目录(默认为 static/)并返回文件的路径.

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.

  • 如果您真的愿意,您可以将路径设置为/static/stylesheets/style.css.但是您真的不应该这样做 - 使用 url_for 可以让您切换静态目录并且仍然可以正常工作,以及其他优点.
  • 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.

而且,正如@RachelSanders 在她的回答中所说:

And, as @RachelSanders said in her answer:

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

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

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

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