[英]how can i do a return render_template() with different variables for the same page - flask python & html
[英]How to render html for variables in Flask render_template
我正在使用 Flask render_template 方法來渲染我的 html 頁面,如下所示:
render_template('index.html', content="<div>Hello World!</div>")
我的 index.html 是:
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
{{content}}
</body>
</html>
我的頁面正在替換內容變量,但它正在將<div>Hello World!</div>
呈現為文本。
有沒有辦法從 render_template 上下文變量中渲染 html ?
Flask 開啟 Jinja 的自動轉義功能。 引用有關如何禁用它的手冊:
有三種方法可以做到這一點:
在 Python 代碼中,將 HTML 字符串包裝在標記 object 中,然后將其傳遞給模板。 這通常是推薦的方式。
在模板中,使用|safe
過濾器將字符串顯式標記為安全 HTML ( {{ myvariable|safe }}
)`
暫時完全禁用自動轉義系統。
如果您不需要將HTML
標簽傳遞到模板中,您可以簡單地做一些看起來像這樣的事情
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
<div>
{{content}}
</div>
</body>
</html>
@app.route('/')
def home():
render_template('index.html', content="Hello World!")
這應該很好。 如果您確實想將 html 添加到您的content
變量中,那么@Ture Pålsson 的答案是最好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.