JavaScript Raises Syntaxerror With Data Rendered in Jinja Template

JavaScript raises SyntaxError with data rendered in Jinja template

Flask's Jinja environment automatically escapes data rendered in HTML templates. This is to avoid security issues if the dev tries to render untrusted user input.

Since you are passing a Python object to be treated as JSON, Flask provides the tojson filter which automatically dumps the data to JSON and marks it safe.

return render_template('tree.html', tree=tree)
var tree = {{ tree|tojson }};

When you just look at the data rendered in HTML, it looks correct because the browser displays the escaped symbols as the real symbols (although in this case you're seeing the string representation of a Python dict, not JSON, so there's still some issues like u markers).

Previous versions of Flask didn't mark the dumped data safe, so you might come across examples like {{ tree|tojson|safe }}, which isn't required anymore.


If you're not rendering JSON (or you already dumped the JSON to a string), you can tell Jinja that data is safe to render without escaping by using the safe filter.

# already dumped to json, so tojson would double-encode it
return render_template('tree.html', tree=json.dumps(tree))
var tree = {{ tree|safe }};

You can also wrap the string in Markup before rendering it, it's equivalent to the safe filter.

# already dumped and marked safe
return render_template('tree.html', tree=Markup(json.dumps(tree)))
var tree = {{ tree }};

If you're not passing this data to JavaScript, but using it in Jinja instead, you don't need JSON. Pass the actual Python data, don't call tojson on it, and use it as you would any other data in the template.

return render_template('tree.html', tree=tree)
{% for item in tree %}
<li>{{ item }}</li>
{% endfor %}

Uncaught SyntaxError: Unexpected token & when passing list/array to Javascript

For safety reasons Jinja is escaping the html in your code.

' is the html code for an '

Information about jinja's html escaping can be found here:
http://jinja.pocoo.org/docs/2.10/templates/#html-escaping

When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe.

So to prevent Jinja from escaping your code you can use Jinja's built in filters.

http://jinja.pocoo.org/docs/2.10/templates/#safe

To mark your code as safe use the safe filter.

var list = {{ array | safe }}

Jinja2 how to ouptput javascript string value

Surround the Jinja expression in quotes so that it is treated as a string in JavaScript.

{% set s = 'Hello! Jinja~' %}
<a href='#' onClick="alert('{{ s }}')">click me</a>

Passing object through jinja converts it to a html encoded text

' is the html encoding for an apostrophe. It has replaced all the apostrophes with the encoding to ensure that the browser will correctly display actual apostrophes. If it did not do this, there it the risk that the browser could interpret it as code which would could be a security issue.

Jinja templating javascript variables

The template only gets evaluated when the page loads, so what the browser sees at that point is essentially static content. You need to pass the dynamic elements into JavaScript so that it can manipulate them while the user is interacting with the page.

I'm no Javascript programmer, but something like

<script>
var cont = 0;
var list = {{list | safe}};
document.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
cont ++;
document.getElementById("divtochange").innerHTML = list[cont];
}
});
</script>

(Added the |safe based on comments.)

Jinja converting quotation marks to '

By default jinja2 engine does the conversion. Update your code as below to use safe filter -

{{ open_modal | safe }}

Javascript won't output to HTML

There's no reason to be using JS here at all. There is nothing interactive here, you should do it directly in Jinja2.

view:

...
return render_template('mytemplate.html', zipped_tests=zip(tests, descriptions))

template:

<tbody>
{% for test, desc in zipped_tests %}
<tr><td>{{ test }}</td><td>{{ desc }}</td></tr>
{% endfor %}
</tbody>

Get ReferenceError when reading data sent by Flask in a js script embedded in a template

In viewer.html, I was not saving the value of {{ chr }} as a string of text.

[..]
<script type="module">
var chr_g = "{{ chr }}";
console.log("chr_g " + chr_g)
</script>

now it works.

How can I read a variable from flask with javascript as an array?

This is because the variable is inside the quotation. But you can't remove the quotation, if you do, it will through syntax error.

You can use JSON.parse

array_total = JSON.parse('{{ array_total|tojson|safe }}')


Related Topics



Leave a reply



Submit