Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to Reference CSS in HTML (python/flask)

Tags:

html

css

flask

I am trying to make a simple website using Python and Flask. Right now, I have the HTML and CSS finished, but my page does not show any of the CSS. My files are in the following hierarchy:

/static
/static/css/style.css
/static/js/skel.js

/templates
/templates/index.html

I have the following code in my html file:

<script src="../static/js/jquery.min.js"></script>
<script src="../static/js/config.js"></script>
<script src="../static/js/skel.min.js"></script>
<script src="../static/js/skel-panels.min.js"></script>

<noscript>    
<link rel="stylesheet" href="../static/css/skel-noscript.css" />
<link rel="stylesheet" href="../static/style.css" />
<link rel="stylesheet" href="../static/css/style-desktop.css" />
</noscript>

When I run this, the terminal displays "304" for the JS files and gets them from "/static/js/skel.js" which I think is correct, but it then displays "404" for the CSS files and gets them from "/css/style.css". I am not quite sure why this is happening - shouldn't this be retrieving files from /static/css/style.css? How can I fix it?

Thanks for the help.

like image 530
kpz Avatar asked Jan 10 '23 17:01

kpz


2 Answers

Your on-disk layout is not the same thing as the routes served by your Flask site. Do not rely on the relative paths between templates and static.

Instead, have Flask calculate the routes to static files for you, using the url_for() function in your Jinja template:

<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/config.js') }}"></script>
<script src="{{ url_for('static', filename='js/skel.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/skel-panels.min.js') }}"></script>

<noscript>    
<link rel="stylesheet" href="{{ url_for('static', filename='css/skel-noscript.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/style-desktop.css') }}" />
</noscript>
like image 177
Martijn Pieters Avatar answered Jan 19 '23 01:01

Martijn Pieters


If the template is really what you have, and your layout is really what you list, then they don't match:

/static/css/style.css

does not match

<link rel="stylesheet" href="../static/style.css" />

Instead you should have

<link rel="stylesheet" href="../static/css/style.css" />

or move style.css up one folder. Note however that IIRC you can't have ../ in path, because static folder is supposed to be at same level as your flask app script. So you should be able to just have

<link rel="stylesheet" href="static/css/style.css" />

but as others have mentioned it is better to have flask generate the url for you via url_for (see example in step 6 of tutorial).

like image 32
Oliver Avatar answered Jan 19 '23 01:01

Oliver