-1

I am learning to build Flask web pages and for some reason, I cannot get any external files (like .js and .css) to be found. It is a basic Flask app:


from flask import Flask, redirect, url_for, render_template

app = Flask(__name__)

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



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

And the HTML file is just HTML boilerplate with the full Bootstrap CDN.

The file paths are as follows:

projfolder/ script.py, templates/ (in templates/)assets/, css/, js/, index.html

The HTML has the filepaths like so:


<script src="assets/mail/jqBootstrapValidation.js"></script>
<script src="assets/mail/contact_me.js"></script>
<script src="js/scripts.js"></script>

I have tried all sorts of file paths and trying to have the files themselves in the same folder as the HTML, same folder as the .py script, and I am at a loss as to why the web page is just not locating those files.

Any help is appreciated.

adomzalski
  • 11
  • 4

1 Answers1

1

According to Flask conventions, Javascript and css files are located inside a directory called static. So, all you need to do is to

  • Create a static folder beside templates
  • Move the assets and js directories to statis
  • In the HTML file, you need to import these files like so:
<script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
<script src="{{ url_for('static', filename='assets/mail/contact_me.js') }}"></script>
<script src="{{ url_for('static', filename='assets/mail/jqBootstrapValidation.js') }}"></script>
Anwarvic
  • 12,156
  • 4
  • 49
  • 69