简体   繁体   English

如何为 Flask 中的变量渲染 html render_template

[英]How to render html for variables in Flask render_template

I am using Flask render_template method to render my html page as below:我正在使用 Flask render_template 方法来渲染我的 html 页面,如下所示:

render_template('index.html', content="<div>Hello World!</div>")

My index.html is:我的 index.html 是:

<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
{{content}}
</body>
</html>

My page is replacing the content variable, but it is rendering <div>Hello World!</div> as text.我的页面正在替换内容变量,但它正在将<div>Hello World!</div>呈现为文本。

Is there a way to render html from render_template context variables?有没有办法从 render_template 上下文变量中渲染 html ?

Flask turns on Jinja's autoescape feature. Flask 开启 Jinja 的自动转义功能。 Quoting the manual on how to disable it:引用有关如何禁用它的手册

There are three ways to accomplish that:有三种方法可以做到这一点:

  1. In the Python code, wrap the HTML string in a Markup object before passing it to the template.在 Python 代码中,将 HTML 字符串包装在标记 object 中,然后将其传递给模板。 This is in general the recommended way.这通常是推荐的方式。

  2. Inside the template, use the |safe filter to explicitly mark a string as safe HTML ( {{ myvariable|safe }} )`在模板中,使用|safe过滤器将字符串显式标记为安全 HTML ( {{ myvariable|safe }} )`

  3. Temporarily disable the autoescape system altogether.暂时完全禁用自动转义系统。

If you do not require passing in HTML tags into the template, you may simply do something that looks like this如果您不需要将HTML标签传递到模板中,您可以简单地做一些看起来像这样的事情


Template模板

<html lang="en">
<head>
<title>Hello</title>
</head>

<body>
    <div> 
        {{content}}
    </div>
</body>

</html>

Python code Python代码

@app.route('/')
def home():
    render_template('index.html', content="Hello World!")

This should be perfectly fine.这应该很好。 If you do want to add html into your content variable, then the answer by @Ture Pålsson is the best way forward.如果您确实想将 html 添加到您的content变量中,那么@Ture Pålsson 的答案是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM