Working with Static Resources CSS JS Image in Flask Template

Introduction

I am going to discuss about working with static resources such as css, js, images in flask template. This tutorial will show you how to use css (Cascading Style Sheet), js (JavaScript) and image files. You need such static resources to generally enhance the look of the web pages and to communicate with the server side code when a user perform an action (using JavaScript) on the web page.

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.

Related Posts:

Including CSS JS Image in Template

Let’s say you have a web application written into flask framework and you use a template file for rendering the UI (User Interface) and the template file’s name is template.html. The standard way of keeping the template file is under templates directory under 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 you can segregate at this level to put them into different folders. Finally you need to 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.

<!DOCTYPE html>
<html>
	<head>
		<title>Including static resources css js images in Flask</title>
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
		<link type="text/css"  rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"/>
		<script type="text/javascript" href="{{ url_for('static', filename='js/sample.js') }}"></script>
	</head>
<body>

	<p>This example shows how to use static resources in flask framework.</p>
	<p><img src="{{ url_for('static', filename='images/image.png') }}" alt="Image" /></p>
	
</body>
</html>

In the above template file notice how did I use url_for() function to include the css, js and image files.

The url_for() function generates a URL to the given endpoint with the method provided.

To include the remote css and js files I have used directly URL of the corresponding CDN (Content Delivery Network).

For the above example I 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.

Leave a Reply

Your email address will not be published. Required fields are marked *