如何将 html 作为变量从 python Flask 传递到 html 中?

Rya*_*ner 5 python flask

在这个例子中:

from flask import Flask, render_template, redirect, session
app = Flask(__name__)
app.secret_key="secret"

@app.route('/')
def landing():
    session['results']="<p>Test one</p>"
    session['results']+="<p>Test two</p>"
    results=session['results']
    return render_template('index.html', results=results)

app.run(debug='True')
Run Code Online (Sandbox Code Playgroud)

在我的 html 中,我有这样的内容:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Game</title>
    </head>
    <body>
    {{ results }}

    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

结果是一个 html 页面,不解释

标签。所以,我得到一个如下所示的页面:

<p>Test One</p><p>Test Two</p>
Run Code Online (Sandbox Code Playgroud)

Mit*_*pta 5

你可以转义 HTML:

{{ results|safe}}
Run Code Online (Sandbox Code Playgroud)

或者用Python

import jinja2
results = jinja2.escape(results)
Run Code Online (Sandbox Code Playgroud)