This seems like a very basic problem but I can’t figure it out. I’m passing a list of URLs into an HTML page and trying to print each one out in an href tag. I’m using Flask to run the test server, and can confirm that the variables are being passed in correctly (I can print out the entire list or elements from it).
My app route:
import doaudit # separate Py script that gets these urls
@app.route('/audit', methods = ['GET'])
def audit():
return render_template('audit.html', listOfUrls = doaudit.listOfUrls)
My template:
<html>
<head>
<title>Data Audit</title>
</head>
<body>
{% for url in listOfUrls %}
<script language="JavaScript">
document.write( "<a href=\"" + url + "\">linktext</a>" );
</script>
{% endfor %}
</body>
</html>
I’ve tried variations on:
document.write( "<a href=\"" + '{{ listOfUrls[i] }}' + "\">linktext</a>" );
and iterating over all the i’s but that doesn’t work either.
The length of the list can vary, so I need an iterative solution. Thanks in advance.
This is what you want:
The
{{ url }}part tells Jinja2 (the template engine) that thisurlis actually the variable that you called so in thefor url in blabla. Without it, it’s printed as is. You can see it when viewing the source in your browser. This means it will be interpreted as a JS variable, which will beundefined, equivalent to an empty string, which you then see.EDIT: added the
tojson|safecalls, to make sure it will not break the JS code. You could do it this way :<a href=\"{{ url }}\">linktext</a>. But then a"would break your html/js code.EDIT 2: what the
tojsonfilter does, is make it suitable to be put inside JS code. and thesafefilter tells the rendering engine that it should not treat it as any text (which should be escaped to show properly in HTML), but treat it as safe text (HTML or not).