Pass JavaScript variable to Flask url_for

Viewed 13424

I have an endpoint that takes a value in the url and produces some content that will be inserted into a div. I want to build the url with url_for using a JavaScript variable. However, $variable1 is passed as a string, rather than the value of variable1. How can I pass the value of a JavaScript variable to url_for?

function myFunction() {
    var variable1 = "someString"
    $('#demo').load(
        "{{ url_for('addshare2', share = '$variable1') }}"
    );
}
3 Answers

Sometimes I use the following workaround with a temporary placeholder string:

var variable1 = "someString";
$('#demo').load(
    "{{ url_for('addshare2', share='ADDSHARE2') }}".replace("ADDSHARE2", variable1)
);

It doesn't feel quite right and I'm still looking for a better solution. But it does the job.

It's possible to send a variable in Jinja by making a template filter to unquote the text returned by url_for()

add this to your app.py:

from urllib.parse import unquote as urllib_unquote

@app.template_filter('unquote')
def unquote(url):
    safe = app.jinja_env.filters['safe']
    return safe(urllib_unquote(url))

then on template do:

function myFunction() {
    var variable1 = "someString"
    $('#demo').load(
        `{{ url_for('addshare2', share = '${variable1}')|unquote }}`
    );
}

this will do the trick.

More on custom template filters: https://flask.palletsprojects.com/en/2.1.x/templating/#registering-filters

Related