Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render html strings in flask templates

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)

and my view function:

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

Firstly, I tried:

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

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?

like image 219
jinglei Avatar asked Feb 05 '16 03:02

jinglei


People also ask

How do I create a render template in Flask?

In this code block, you import the Flask class and the render_template() function from the flask package. You use the Flask class to create your Flask application instance named app . Then you define a view function (which is a Python function that returns an HTTP response) called hello() using the app.


1 Answers

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 }}
like image 111
Joran Beasley Avatar answered Oct 02 '22 16:10

Joran Beasley