9

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.

1
  • use <script src="{{url_for('static', filename='main_scripts.js')}}"></script>, when you are in a sub route(ie: `/user/info') the relative path will be different. Commented Sep 21, 2017 at 17:04

1 Answer 1

30

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 ... 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
When I try this, my IDE suggests that the syntax is wrong. Do I need to escape the quotation marks somehow?
@Rylan Schaeffer: Here is the correct syntax with all single quotes within the double: <script src="{{ url_for('static', filename='js/main_scripts.js') }}"></script>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.