烧瓶和HTML变量

时间:2018-12-29 17:53:47

标签: python flask jinja2 jupyter nbconvert

我是flask的新手,但是希望将其他库中的一些HTML功能与flask的模板功能集成在一起。在玩弄变量时,我无法理解呈现HTML的不同行为。有时候,如果我将HTML作为变量直接传递给视图,则可以获得HTML呈现:

body = a bunch of HTML
@app.route('/')
def index():
    return '''
    {}
    '''.format(body)

但是,如果我尝试使用{{body}}变量将其传递给模板,则不会呈现HTML。相反,我将在页面上看到原始HTML。

@app.route('/')
def index():
     return render_template("index.html", b = body)

在“ index.html”文件中,我使用{{ b }}模板语法来称呼它。在这里,我得到了原始HTML。我觉得我只想念一小部分。这是我分别对每种方法看到的内容。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

Jinja将转义它解析的所有字符串,以避免意外将HTML注入模板。要将变量标记为“可以按原样安全使用”,您需要使用safe模板过滤器。

{{ b|safe }}

>>> b = '<a href="#">Example</a>'

>>> render_template_string('{{ b }}', b=b)                                                
'&lt;a href=&#34;#&#34;&gt;Example&lt;/a&gt;'

>>> render_template_string('{{ b|safe }}')                                           
'<a href="#">Example</a>'