Flask url_for URLs in Javascript Flask url_for URLs in Javascript flask flask

Flask url_for URLs in Javascript


What @dumbmatter's suggesting is pretty much considered a de facto standard way. But I thought there would be a nicer way of doing it. So I managed to develop this plugin: Flask-JSGlue.

After adding {{ JSGlue.include() }}, you can do the following in your source code:

<script>    $.post(Flask.url_for('comment.comment_reply', {article_id: 3}));</script>

or:

<script>    location.href = Flask.url_for('index', {});</script>


The Flask documentation suggests using url_for in your HTML file to set a variable containing the root URL that you can access elsewhere. Then, you would have to manually build the view URLs on top of that, although I guess you could store them similar to the root URL.


Was searching for a solution, them come up with this solution where

  • No add-on is required

  • No hard-coding URL

The key is to realise Jinja2 has the ability to render javascript out of the box.


Setup your template folder to something like below:

/template    /html        /index.html    /js        /index.js

In your views.py

@app.route("/index_js")def index_js():    render_template("/js/index.js")

Now instead of serving the javascript from your static folder. You would use:

<script src="{{ url_for('index_js') }}"></script>

After all, you are generating the javascript on the fly, it is no longer a static file.


Now, inside of you javascript file, simply use the url_for as you would in any html file.

For example using Jquery to make an Ajax request

$.ajax({  url: {{ url_for('endpoint_to_resource') }},  method: "GET",  success: call_back()})