[英]How do I convert md files to HTML and render them in Django
I have some md files in an 'entries' folder in my django app folder and i wanna get them, covert them to HTML then render them.我的 django 应用程序文件夹的“条目”文件夹中有一些 md 文件,我想获取它们,将它们转换为 HTML 然后渲染它们。 This is my util.py
这是我的 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
This is my views.py这是我的意见.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."
})
I also have...我也有...
path("wiki/<str:topic>", views.wiki)
in my urls.py but I'm still getting a FileNotFoundError at /wiki/Python error Note: I have pip installed markdown在我的 urls.py 但我仍然在 /wiki/Python 错误处收到 FileNotFoundError注意:我安装了 pip markdown
pip install markdown
on your console/terminal. pip install markdown
。
Then try the following:然后尝试以下操作:
import markdown
f = open("MDFile.md","r")
f = f.read()
html = markdown.markdown(f)
where MDFile.md are your markdown files.其中 MDFile.md 是您的 markdown 文件。
html
will have the HTML version of your markdown file. html
将具有 markdown 文件的 HTML 版本。
I was facing same filenotfound exception, but i have found the answer finally.我面临同样的 filenotfound 异常,但我终于找到了答案。 Md files are located in entries folder, so you have to specify that in convert_Md function in utils.py just like in get_entry function.
Md 文件位于条目文件夹中,因此您必须在 utils.py 中的 convert_Md function 中指定它,就像在 get_entry function 中一样。
file = default_storage.open(f"entries/{filename}.md", "r") I hope this will fix your issue as it did mine. file = default_storage.open(f"entries/{filename}.md", "r") 我希望这能像解决我的问题一样解决您的问题。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.