在烧瓶模板中呈现html字符串 [英] render html strings in flask templates

查看:65
本文介绍了在烧瓶模板中呈现html字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网页来显示文章. 在我的数据库中,我必须具有属性,其中一个属性用于放置Markdown代码,另一个属性用于保存从Markdown代码转换而来的HTML代码.我想获取HTML并将其添加到我的基本HTML中. 我使用Flask框架和SQLAlchemy,数据保存在sqlite数据库中. 我的模特:

I'm building a web page to show articles. In my database, I have to attributes, one of which is used to put Markdown code and the other to save HTML code converted from the Markdown code. I want to get the HTML and add it to my base HTML. I use Flask framework and SQLAlchemy and the data is saved in sqlite database. My model:

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文件中?

It shows the whole string with HTML tag. post.body.decode("utf-8") and post.body.decode("ascii") didn't work, either. When I debug the program, I found that the database returns u'string'. How can I get pure HTML code and apply it in my base HTML file?

推荐答案

默认情况下jinja2(flask的模板引擎)假定{{ }}内部的输入不安全,并且不允许在其中输入js或html.可以通过使用模板内的safe过滤器解决此问题.这将告诉jinja2,内容可以按原样呈现,并且不会逃脱html/javascript

by default jinja2 (the template engine for flask) assumes input inside of {{ }} is unsafe and will not allow js or html inside of them ... you can solve this by using the safe filter inside your template. this will tell jinja2 that the content is safe to render as is, and not to escape the html/javascript

{{ post.body | safe }}

这篇关于在烧瓶模板中呈现html字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆