簡體   English   中英

如何將 md 文件轉換為 HTML 並在 Django 中呈現它們

[英]How do I convert md files to HTML and render them in Django

我的 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 但我仍然在 /wiki/Python 錯誤處收到 FileNotFoundError注意:我安裝了 pip markdown

pip install markdown

然后嘗試以下操作:

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

其中 MDFile.md 是您的 markdown 文件。 html將具有 markdown 文件的 HTML 版本。

我面臨同樣的 filenotfound 異常,但我終於找到了答案。 Md 文件位於條目文件夾中,因此您必須在 utils.py 中的 convert_Md function 中指定它,就像在 get_entry function 中一樣。

file = default_storage.open(f"entries/{filename}.md", "r") 我希望這能像解決我的問題一樣解決您的問題。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM