首页 > 解决方案 > 没有格式的 Python Flask 博客消息

问题描述

我有一个简单的消息博客的代码,可以留言。问题之一是来自 sqlite db 的消息显示没有格式,例如没有段落。我怎样才能改进它(或添加降价启用)?我感谢您的帮助。谢谢你。

主应用 py

@app.route('/')
def index():
    conn = db_conn()
    posts = conn.execute('SELECT * FROM table_posts').fetchall()
    conn.close()
    return render_template('index.html', posts=posts)

@app.route('/create_new_post', methods=('GET', 'POST'))
def create_new_post():
    if request.method == 'POST':
        content = request.form['content']

        conn = db_conn()
        conn.execute('INSERT INTO table_posts (content) VALUES (?)', (content,))
        conn.commit()
        conn.close()
        return redirect(url_for('index'))
    else:
        return render_template('create_new_post.html')

索引.html

{% extends 'base.html' %}

{% block title %}
    Simple Message Board
{% endblock %}

{% block content %}
    {% for post in posts %}
        <br>
        <div class="card">
            <div class="card-body">
                <p class="card-text"> {{ post['content'] }} </p>
                <span class="badge badge-secondary">{{ post['time_stamp'] }}</span>
            </div>
        </div>
    {% endfor %}
{% endblock %}

我想要的结果如下:

Text of 1st line
Text of 2nd line
Text of 3rd line

但实际显示的内容如下:

Text of 1st line Text of 2nd line Text of 3rd line

标签: pythonhtmlsqliteflask

解决方案


我认为您正在尝试将正文呈现为 html 而不是文本。

jinja 自动转义文本,您可以停止自动转义,为此您可以使用 jinja 的安全过滤器。

{{ post['content']|safe }} 

您还可以查看文档


推荐阅读