Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask url_for URLs in Javascript

What is the recommended way to create dynamic URLs in Javascript files when using flask? In the jinja2 templates and within the python views url_for is used, what is the recommended way to do this in .js files? Since they are not interpreted by the template engine.

What basically want to do is:

// in comments.js $.post(url_for('comment.comment_reply')); 

Which is not possible.

But naturally, I can execute that in a template:

<script>     $.post(url_for('comment.comment_reply')); </script> 
like image 450
Erik Rothoff Avatar asked Apr 25 '12 11:04

Erik Rothoff


1 Answers

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> 
like image 61
Stewart Park Avatar answered Sep 28 '22 17:09

Stewart Park