sha*_*vey 142 python jinja2 flask
我正在为Flask和SQLAlchemy构建一个管理员,我想将不同输入的HTML传递给我的视图render_template.模板框架似乎自动转义html,因此所有<"'>都转换为html实体.如何禁用它以便HTML呈现正确?
iam*_*pal 295
理想的方式是
{{ something|safe }}
Run Code Online (Sandbox Code Playgroud)
而不是完全关闭自动逃逸.
Arm*_*her 99
您还可以从代码中声明HTML安全:
from flask import Markup
value = Markup('<strong>The HTML String</strong>')
Run Code Online (Sandbox Code Playgroud)
然后将该值传递给模板,他们没有|safe它.
dar*_*lff 19
从jinja docs部分HTML Escaping:
启用自动转义功能后,除默认标记为安全的值外,默认情况下都会转义所有内容.这些可以由应用程序标记,也可以使用安全过滤器在模板中标记.
例:
<div class="info">
{{data.email_content|safe}}
</div>
Run Code Online (Sandbox Code Playgroud)
Nie*_*kob 14
当您有很多不需要转义的变量时,您可以使用autoescape覆盖块:
{% autoescape false %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split function) and also doesn't add an unnecesssary <br/> after the last item.
| 归档时间: |
|
| 查看次数: |
86764 次 |
| 最近记录: |