【问题标题】:Error in converting from markdown to editor in flask在烧瓶中从 Markdown 转换为编辑器时出错
【发布时间】:2019-04-08 02:48:54
【问题描述】:

我在 python 中使用 markdown 库在我的烧瓶应用程序中显示一些 markdown。 我在显示输出时遇到错误,因为它显示的是降价内容而不将其转换为 HTML。

这是我的 Python 代码。

import markdown
from flask import Flask
#import some other libraries

@app.route('/md')
def md():
    content = """
    <h1>Hello</h1>
    Chapter
    =======

    Section
    -------

    * Item 1
    * Item 2
    **Ishaan**
    """

    content = Markup(markdown.markdown(content))
    return render_template('md.html', **locals())

这是我的 html 代码。

<html>
  <head>
    <title>Markdown Snippet</title>
  </head>
  <body>
    {{ content }}
  </body>
</html>

我正在关注here的代码

我知道我做错了,但如果有人帮助我,我将不胜感激。 提前致谢。

【问题讨论】:

    标签: python flask markdown


    【解决方案1】:

    减少你的 Markdown 行。

    Python 三引号内的任何内容都由 Python 字面解释。这包括缩进。因此,传递给 Markdown 的文本会缩进一级,导致 Markdown 将整个文档解释为代码块。删除缩进,Markdown 将正确识别文本:

    @app.route('/md')
    def md():
        content = """
    <h1>Hello</h1>
    Chapter
    =======
    
    Section
    -------
    
    * Item 1
    * Item 2
    **Ishaan**
    """
    

    请注意,您复制的示例也不会缩进三引号文本。当然,这会降低您的 Python 代码的可读性。因此,Python 标准库包含 textwrap.dedent() 函数,它将以编程方式删除缩进:

    from textwrap import dedent
    
    @app.route('/md')
    def md():
        content = """
        <h1>Hello</h1>
        Chapter
        =======
    
        Section
        -------
    
        * Item 1
        * Item 2
        **Ishaan**
        """
    
        content = Markup(markdown.markdown(dedent(content))) # <= dedent here
    

    请注意,content 在传递给 Markdown 之前先通过 dedent

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 2018-05-22
      • 2020-08-14
      • 1970-01-01
      • 2020-10-13
      相关资源
      最近更新 更多