【问题标题】:How do I convert md files to HTML and render them in Django如何将 md 文件转换为 HTML 并在 Django 中呈现它们
【发布时间】:2021-06-08 09:18:18
【问题描述】:

我的 django 应用程序文件夹的“条目”文件夹中有一些 md 文件,我想获取它们,将它们转换为 HTML,然后渲染它们。 这是我的 util.py

def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None


def convert_md(filename):
    """
    Converts given md file to html
    """
    #file= f"{filename}.md"

    file= default_storage.open(f"{filename}.md")
    md= file.read()
    html= md.markdown(md)
    return html
    

这是我的观点.py

def wiki(request, topic):
    if util.get_entry(topic) != None:
        html= util.convert_md(topic)
        return render(request, "encyclopedia/pages.html", {
            "title": topic, "body": html 
        })
    else:
        return render(request, "encyclopedia/pages.html", {
            "title": "ERROR", "body": "THIS PAGE IS NOT AVALIABLE."
        })

我也有……

path("wiki/<str:topic>", views.wiki)

在我的 urls.py 中,但我仍然收到 FileNotFoundError at /wiki/Python 错误 注意:我已经pip安装了markdown

【问题讨论】:

    标签: python html django markdown


    【解决方案1】:

    pip install markdown 在您的控制台/终端上。

    然后尝试以下操作:

    import markdown
    f = open("MDFile.md","r")
    f = f.read()
    html = markdown.markdown(f)
    

    其中 MDFile.md 是您的降价文件。 html 将拥有您的 Markdown 文件的 HTML 版本。

    【讨论】:

    • 注意:如果要一次处理多个 md 文件,只需使用循环即可。希望这会有所帮助!
    猜你喜欢
    • 2021-01-07
    • 2020-05-14
    • 2018-01-19
    • 2019-09-25
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多