13

I'm developing a flask app with the following folder structure:

|-->flask_app.py
    |-->static
        |-->css
            |-->bootstrap.min.css
            |-->styles.css
        |-->js
            |-->jquery-3.1.1.min.js
            |-->bootstrap.min.js
            |-->script.js
    |-->templates
        |-->index.html

What is the proper way to link to these css and js files in index.html and what parameters do I need associated with them?

My CSS links look like this and are located in the header:

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

And my JS links look like this and are located at the end of the body tag:

<script src="{{ url_for('static', filename='js/script.js') }}"></script>

Is this the correct syntax? Are they located in the correct spots in my templates (I'm sure there's flexibility here)? And are there any other parameters I should pass in (e.g. type="text/css", type="text/javascript", media="screen")?

Everything is working as expected but I want to follow recommended practice if there is any.

davidism
  • 121,510
  • 29
  • 395
  • 339
Johnny Metz
  • 5,977
  • 18
  • 82
  • 146
  • 1
    There's a syntax error in the script tag you've posted here but otherwise it looks about right to me. Is it not working? You can configure the static directory (see the API: http://flask.pocoo.org/docs/0.11/api/) as well but it defaults to `static` – hammygoonan Dec 21 '16 at 03:05
  • Code is working fine. Just making sure this is correct. Syntax error fixed btw, good catch. – Johnny Metz Dec 21 '16 at 18:49
  • On a related note, [Flask's Static Files](http://stackoverflow.com/documentation/flask/3678/static-files#t=201612211932275463453) is a topic covered in the new Documentation section here on StackOverflow. – YellowShark Dec 21 '16 at 19:34
  • This is fine and has worked very well for me. No issues. – Johnny Metz Nov 01 '17 at 15:51
  • @YellowShark Not anymore. –  Nov 07 '18 at 12:20

1 Answers1

3

As the Flask documentation mentions, you should store .css and .js files within your static folder and for organizational purposes, its fine to have each type of file as subdirectories (especially as your app grows).

Per this SO answer, you don't need to have type="text/css" or type="text/javascript" in the jinja expression.

deesolie
  • 867
  • 7
  • 17