Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a JavaScript variable into Flask url_for() function?

I have following code in my Flask template:

<div id="cell1"></div>
<script>
var id="0014";
cell1.innerHTML = '<a href={{url_for('static',filename='+id+'".txt")}}">'+id+'</a>';
</script>

I want the link to render to:

http://my_address/static/0014.txt

But I got this:

http://my_address/static/+id+.txt 

How to make the js variable id in Flask url_for() function work?

Thanks for your help!

like image 472
Juan Prado Avatar asked Aug 02 '26 20:08

Juan Prado


1 Answers

Try this:

cell1.innerHTML = '<a href={{ url_for('static', filename='') }}' + id + '.txt>' + id + '</a>';

url_for() will generate an URL like this: .../static/<filename>. If you use url_for('static', filename=''), it generate an URL like: .../static/, so you can just add text after it (i.e. + id + '.txt>') .

like image 108
Grey Li Avatar answered Aug 05 '26 10:08

Grey Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!