Span元素未用撇号替换&#39

2024-10-03 04:37:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过javascript中的jinja2将文本传递到code mirror文本编辑器库元素。你知道吗

code = `{% for line in file_content%}{{ line }}\n{% endfor %}`

//CODE MIRROR
var editor = CodeMirror(document.getElementById('code_editor'), {
    value: code,
    mode: 'python',
    theme: 'neo'
});

如果file_content被设置为一些Python代码,例如["self._tophash = ''"],则生成以下HTML元素:

<div id='code_editor'>
   <span role="presentation" style="padding-right: 0.1px;">        
        self._tophash = &amp;#39;&amp;#39;
   </span>
</div>

尽管当它打印到屏幕上时,HTML显示为&#39;,而不是'

有人知道为什么会这样吗?你知道吗


Tags: 文本selfdiv元素jinja2mirrorhtmlline
1条回答
网友
1楼 · 发布于 2024-10-03 04:37:58

金盏2永远是HTML escape anything you insert into a document。这包括转义引号字符,因为这些字符可用于“中断”HTML属性,从而使站点面临交叉脚本攻击。你知道吗

您必须明确地将数据标记为“安全”:

code = `{% for line in file_content%}{{ line|safe }}\n{% endfor %}`

就我个人而言,我会将数据插值为JSON

code = {{ file_content|join('\n')|tojson }};

JSON几乎完全是Javascript的一个子集;Jinja2 ^{} filter将Python数据编码为JSON的方式保证与Javascript兼容。你知道吗

如果您使用的是Jinja2older than 2.10(Flask 1.0的最低版本),您仍然需要将结果标记为安全的,但这在这里很好,因为您不会生成插入到HTML元素或属性中的数据。你知道吗

相关问题 更多 >