WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Flask – Static Files


A web application regularly requires a static file for example, a javascript record or a CSS file supporting the showcase of a site page. For the most part, the web server is arranged to serve them for you, however during the advancement, these records are served from static organizer in your bundle or beside your module and it will be accessible at/static on the application.

A extraordinary endpoint 'static' is utilized to create URL for static files.

In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

The HTML script of index.html is given below.

<html>
   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

hello.js contains sayHello() function.

function sayHello() {
   alert("Hello World")
}