Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Application - How to link a javascript file to website

I am having some trouble getting started with using javascript files on my website (A Flask application). I start the website by running run.py which looks like this:

#!flask/bin/python
from app import app
app.run(debug=True)

In my html page I have the following code which gives a 404 error:

404 error

Error message:

error message

My file structure looks like this:

file structure

Any hints to where I'm going wrong?

like image 974
user2260199 Avatar asked May 03 '15 07:05

user2260199


People also ask

How do I add a JavaScript file to my website?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I link a website to my Flask?

In websites hyperlinks are used to link one page to another. This is done in Flask by using your well known anchor tag (<a href=””> link text</a>). In Flask href destination is set in context to the route defined in the application.py file.


2 Answers

Ah yes, luckily I am currently developing a flask application at the moment.

You are currently missing the static folder which by default flask looks into, a folder structure something like this:

|FlaskApp
----|FlaskApp
--------|templates
        - html files are here
--------|static
        - css and javascript files are here

Two important default folders that Flask will look into templates and static. Once you got that sorted you use this to link up with your javascript files from your html page:

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

Hope that helps any questions just ask.

Plus - A good article to read but not super related but it talks about the folder structure of flask is this: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps

like image 68
jonprasetyo Avatar answered Oct 10 '22 23:10

jonprasetyo


So your index.html is at app/templates/index.html, and your jQuery is at app/javascript/jQuery.js right?

I think your path is wrong. Try this:

<script src="../javascript/jquery.js"></script>
like image 33
Anakin Avatar answered Oct 10 '22 23:10

Anakin