6

I'm using Python and Flask to build a simple interaction web app. Testing on localhost:5000 using Chrome.

I have one template and one associated javascript file located at: ./templates/main.html ./templates/main_scripts.js

The main.html template includes the scripts file like this:

<script src="main_scripts.js"></script>

When I render the template using this Python code...

return render_template('main.html', session_id=session_id, title=sess.title)

The main.html page is rendered, but I get this error in the Chrome console:

Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Using the Chrome console to inspect the location of the unfound 'main_scripts.js' when the error occurs, the browser thinks it is trying to load it from inside my virtual environment at:

./env/Scripts/main_scripts.js

...and not from the same directory as the template.

I can't seem to force the rendered template to understand where it's script file is located. So far I have tried src paths like "./main_scripts.js" and even "/appdir/main_scripts.js" with the exact same results.

vbsql7
  • 684
  • 2
  • 9
  • 17

1 Answers1

27

You first need to create a static folder at the same level as the templates folder. Then create a js subfolder and put the js file in that folder. Now you can call it in your html.
Here's the "pythonic" way do that:

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

As explained here in the official Flask documentation, your project structure should look like this:

/yourapplication
    yourapplication.py
    /static
        /css
            style.css
        /js
            main_scripts.js
    /templates
        main.html
        ...
Espoir Murhabazi
  • 5,973
  • 5
  • 42
  • 73
  • 1
    Thank you Espoir for taking the time both to answer and to link to the larger reference source. I searched quite a while for this answer but I guess I was using the wrong terms. – vbsql7 Sep 25 '17 at 18:00
  • When I try this, my IDE suggests that the syntax is wrong. Do I need to escape the quotation marks somehow? – Rylan Schaeffer Feb 10 '22 at 22:57
  • 1
    @Rylan Schaeffer: Here is the correct syntax with all single quotes within the double: `````` – Sergiy Savelyev Aug 08 '22 at 23:39