【问题标题】:The string return from markdown can't work if I insert into a HTML? [duplicate]如果我插入 HTML,markdown 返回的字符串不起作用? [复制]
【发布时间】:2019-12-30 05:12:13
【问题描述】:

我正在学习烧瓶网络框架。并且遇到这个问题。 我从用户那里得到一些 Markdown 样式的文本,然后将其转换为 HTML 并存储在数据库中。

title = request.form.get('title')
content = request.form.get('content')
html = markdown(content)
newPost = Article(title, html)
db.session.add(newPost)
db.session.commit()

当我从数据库中提取标题和内容并将其直接插入 HTML 时,似乎不起作用。

#view.py
articles = Article.query.all()
print(articles[0].body) # <h3>Test</h3>
<div class="container mb-5">
    <span class="row">
        <h4>{{ articles[0].title }}</h4>
    </span>
    <span class="row mt-3 mb-3">
        <span class="mr-2"><time>{{ articles[0].pub_date.strftime('%B %d %Y') }}</time></span>
    </span>
    <div class="row">
        {{ articles[0].body }}
    </div>
</div>

我从 chrome 开发工具中复制了该元素,正文字符串实际上是:

<div class="row">
    &lt;h3&gt;Test&lt;/h3&gt;
</div>

这与编码有关吗?接下来我该怎么做?

谢谢!

【问题讨论】:

    标签: python flask markdown


    【解决方案1】:

    出于安全原因,Flask/Jinja2 更改了 HTML 中的一些字符,但您可以使用 | safe 通知 Flask/Jinja2 此文本是安全的,无需更改

    {{ articles[0].body | safe }}
    

    文档:Jinja2: Working with Automatic Escaping

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多