Separating html and JavaScript in Flask

Question:

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!

Asked By: ChristianK

||

Answers:

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.

Answered By: metatoaster
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.