Every web framework has its own style of including such static resource files. Flask also has its own style to include such resources, css, js and image files, into web pages.
Including CSS JS Image in Template
Let’s say you have a web application written into flask framework and the template file name is template.html. The standard way of keeping the template file is under templates directory of the project root directory.
It’s always better to keep the static resources under separate directories according to their usage type. The standard of keeping static resources in flask framework under static directory of the project root directory.
Now it’s not a good idea if we put css, js and images under a single static directory. So we can segregate at this level to put them into different folders. Finally we keep css under static/css directory, js under static/js directory and images under static/images directory.
Let’s look at the following template file.
In the above template file notice how did we use
url_for() function to include the css, js and image files.
url_for() function generates a URL to the given endpoint with the method provided.
To include the remote css and js files we have used directly URL of the corresponding CDN (Content Delivery Network).
For the above example we have assumed that the static files such as main.css, sample.js and image.png are kept under the css, js and images of project root directory, respectively.
Hope you understand how to include static resources such as css, js and images into web application using flask framework.
Thanks for reading.Tags: Template