簡體   English   中英

在flask模板中渲染html字符串

[英]render html strings in flask templates

我正在建立一個網頁來展示文章。 在我的數據庫中,我必須使用屬性,其中一個用於放置Markdown代碼,另一個用於保存從Markdown代碼轉換的HTML代碼。 我想獲取HTML並將其添加到我的基本HTML。 我使用Flask框架和SQLAlchemy ,數據保存在sqlite數據庫中。 我的模特:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    body = db.Column(db.String)
    timestamp = db.Column(db.String)
    tag = db.Column(db.String)
    info = db.Column(db.String)
    body_markdown = db.Column(db.String)

和我的觀點功能:

def post(post_id):
    post = db.session.query(Post).filter(Post.id == post_id).first()
    return render_template('post.html',
                           post = post,)

首先,我試過:

<div class="post-body">
    {{post.body}}
</div>

它顯示帶有HTML標記的整個字符串。 post.body.decode("utf-8")post.body.decode("ascii")也沒有用。 當我調試程序時,我發現數據庫返回了你的u'string' 如何獲取純HTML代碼並將其應用於我的基本HTML文件?

默認情況下,jinja2(燒瓶的模板引擎)假定{{ }}內部的輸入是不安全的,並且不允許在其中使用js或html ...您可以通過在模板中使用safe過濾器來解決此問題。 這將告訴jinja2內容可以安全地呈現,而不是逃避html / javascript

{{ post.body | safe }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM