Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: where to put static javascript files in templates

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.

like image 658
Johnny Metz Avatar asked Dec 20 '16 20:12

Johnny Metz


People also ask

Where do you put static files in a Flask?

Ideally, you should use a dedicated HTTP server (like Apache or Nginx) in front of your Flask application to serve your static files in production. You need to create a folder called static in your application's root directory to store all your static files.

What should be in a static folder Flask?

Folder structure for a Flask app That folder contains two folders, specifically named static and templates. The static folder contains assets used by the templates, including CSS files, JavaScript files, and images.

How do I change my static folder in Flask?

It turns out the official Flask docs specify that the static url path is configurable using the 'static_url_path' parameter to the Flask application initializer. to include the static_url_path set to something useful like /public will do the trick. And voila, problem solved!

Where is the Flask Templates folder?

By default, Flask looks for templates in the subdirectory named templates inside the application folder. We can change this default behavior by passing template_folder argument to the Flask constructor at the time of creating application instance.


1 Answers

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.

like image 105
deesolie Avatar answered Sep 23 '22 14:09

deesolie