How to set flask url_for in JQuery
Here goes with an example, I never really considered needing url_for
to be accessed from the user-interface, but it's good to know how. When you click on a button, it'll use the id
as the key to the url_for
and show the resulting URL in an alert box.
requirements.txt
flaskgit://github.com/dantezhu/flask_util_js.git
Then install them, pip install -r requirements.txt
into your virtualenv.
app.py
from flask import Flask, render_templatefrom flask_util_js import FlaskUtilJsapp = Flask(__name__)fujs = FlaskUtilJs(app)@app.context_processordef inject_fujs(): return dict(fujs=fujs)@app.route('/')def home(): return render_template('example.html')@app.route('/foo/<something>/')def something(something): return 'Alright then {}'.format(something)if __name__ == '__main__': app.run(debug=True)
example.html
<html><head> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> {{ fujs.js }} <script> $( document ).ready(function(){ $("button").on("click", function() { var $button = $( this ); var url = flask_util.url_for('something', {something: $button.attr('id') }); alert(url); }); }); </script></head><body> <button id="button_a">First!</button> <button id="button_b">Second!</button> <button id="button_c">Third!</button></body></html>