3

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!

4
  • Could it be that you are mixing server side and client side code? What's this {{url_for(...)}} stuff, some sort of template engine method? If so, you need to work on the result of the function call. Commented Nov 12, 2016 at 23:11
  • 2
    I think you've a quotes issue, try to use cell1.innerHTML = '<a href={{url_for("static", filename="'+id+'.txt")}}">'+id+'</a>'; Commented Nov 12, 2016 at 23:12
  • Quotes escape '<a href={{url_for("static",filename="'+id+'.txt")}}">'+id+'</a>' Commented Nov 12, 2016 at 23:16
  • Thanks Quagaar and Zakaria Achrki for yours suggestions. Grey Li gave me the solution. Commented Nov 13, 2016 at 14:31

1 Answer 1

4

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>') .

Sign up to request clarification or add additional context in comments.

2 Comments

Dear, Thank you very much! It Works!
sorry, for the moment I not have sufficient reputation for vote, but when I have it will do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.