应用程序未获取 .css 文件(flask/python) [英] Application not picking up .css file (flask/python)

查看:32
本文介绍了应用程序未获取 .css 文件(flask/python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在渲染一个模板,我正在尝试使用外部样式表对其进行样式设置.文件结构如下.

I am rendering a template, that I am attempting to style with an external style sheet. File structure is as follows.

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /styles
        - mainpage.css

mainpage.html 看起来像这样

mainpage.html looks like this

<html>
    <head>
        <link rel= "stylesheet" type= "text/css" href= "../styles/mainpage.css">
    </head>
    <body>
        <!-- content --> 

虽然我的任何样式都没有被应用.它与 html 是我正在渲染的模板这一事实有关吗?蟒蛇看起来像这样.

None of my styles are being applied though. Does it have something to do with the fact that the html is a template I am rendering? The python looks like this.

return render_template("mainpage.html", variables..)

我知道这一切都在起作用,因为我仍然能够渲染模板.但是,当我尝试将样式代码从 html 的head"标记内的样式"块移动到外部文件时,所有样式都消失了,留下了一个裸露的 html 页面.有人看到我的文件结构有什么错误吗?

I know this much is working, because I am still able to render the template. However, when I tried to move my styling code from a "style" block within the html's "head" tag to an external file, all the styling went away, leaving a bare html page. Anyone see any errors with my file structure?

推荐答案

除非您在 Flask 初始化期间专门覆盖它,否则您需要有一个静态"文件夹设置(用于 css/js 文件).我假设你没有覆盖它.

You need to have a 'static' folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.

你的 css 目录结构应该是这样的:

Your directory structure for css should be like:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

注意你的/styles 目录应该在/static 下

Notice that your /styles directory should be under /static

然后,这样做

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

Flask 现在会在 static/styles/mainpage.css 下寻找 css 文件

Flask will now look for the css file under static/styles/mainpage.css

这篇关于应用程序未获取 .css 文件(flask/python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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