Passing HTML to template using Flask/Jinja2

2018-12-31 04:45发布

I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework seems to escape the html automatically, so all <"'> are converted to html entities. How can I disable that so that the HTML renders correctly?

3条回答
人间绝色
2楼-- · 2018-12-31 05:08

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

查看更多
明月照影归
3楼-- · 2018-12-31 05:12

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don't have to |safe it.

查看更多
怪性笑人.
4楼-- · 2018-12-31 05:12

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>
查看更多
登录 后发表回答