I am passing text into the code mirror text editor library element through jinja2 in javascript.
code = `{% for line in file_content%}{{ line }}\n{% endfor %}`
//CODE MIRROR
var editor = CodeMirror(document.getElementById('code_editor'), {
value: code,
mode: 'python',
theme: 'neo'
});
If file_content
is set to some Python code such as ["self._tophash = ''"]
then this produces the following HTML element:
<div id='code_editor'>
<span role="presentation" style="padding-right: 0.1px;">
self._tophash = &#39;&#39;
</span>
</div>
Although when it prints to screen the HTML shows as '
rather than '
Does anyone know why this is happening?
Jinja2 will always HTML escape anything you insert into a document. This includes escaping quote characters, as these could be used to 'break out' of HTML attributes, opening your site to a cross-scripting attack.
You'd have to mark the data as 'safe' explicitly:
code = `{% for line in file_content%}{{ line|safe }}\n{% endfor %}`
Personally, I'd interpolate the data as JSON instead:
code = {{ file_content|join('\n')|tojson }};
JSON is (almost entirely) a subset of Javascript; the way the Jinja2 tojson
filter encodes Python data to JSON is guaranteed to be Javascript compatible.
If you are using a version of Jinja2 older than 2.10 (the minimal version for Flask 1.0), you still have to mark the result as safe, but that's fine here since you are not producing data that is interpolated into an HTML element or attribute.