23

Hey I've got the following problem:

I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:

Assume I have a simple flask web app called app.py located in my_app/ which looks like this

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

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

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

and the corresponding index.html, which is located in my_app/templates, is simply

<!DOCTYPE html>
<html>
<body>

<p>Clicking here will make me dissapear</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">            </script>
<script>
$(document).ready(function() {
    $("p").click(function(event){
        $(this).hide();
    });
});
</script>
</body>
</html>

then I see the expected result, that is, i can click on the paragraph to make it disappear.

BUT: I would like to put the javascript part into a main.js file under static/js/. like so:

$(document).ready(function() {
    $("p").click(function(event){
        $(this).hide();
    });
});

and the index.html becomes:

<!DOCTYPE html>
<html>
<body>

<p>Clicking here will make me dissapear</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>            
</body>
</html>

Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!

ChristianK
  • 233
  • 1
  • 2
  • 5
  • When you hit that URL "/js/main.js" in the browser (type it right into the search bar), is the file there? – Josh KG Mar 22 '16 at 23:31
  • Hey Josh, I can see it under http://127.0.0.1:8080/static/js/main.js. Since, as far as i know, Flask looks for such files in the static folder I thought this needed to be omitted. Obviously i was wrong concerning that. – ChristianK Mar 23 '16 at 09:41

1 Answers1

33

Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created. As the desired target is the main.js file inside static/js, this would lead to the following:

<script type=text/javascript src="{{
  url_for('static', filename='js/main.js')
}}"></script>

The rest of the quickstart guide contains additional useful information.

metatoaster
  • 17,419
  • 5
  • 55
  • 66