两种方法
Django 的
django-markdown-deux模块Python模块
markdown
django-markdown-deux
首先需要安装:
pip install django-markdown-deux
修改setting.py
把markdown-deux添加进去
INSTALLED_APPS = [ 'markdown-deux', ]
在模板里添加tags
加载了markdown-deux-tags标签之后,在markdown内容加上过滤器就可以解析成html了。
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Doc - {{ docname }}</title>
<link href="/static/css/highlights/github.css"/></head><body>{ % load markdown-deux-tags % }
{{ content | markdown }}</body></html>使用markdown模块渲染
首先安装
pip install markdown
在views.py里使用markdown渲染
import markdowndef doc(request, name):
template = get_template('doc.html')
docfile = get_template('doc/{}.md'.format(name))
content = docfile.render()
html = template.render({ 'docname': name, 'content':
markdown.markdown(content,
extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc',
])
}) return HttpResponse(html)markdown模块会直接把markdown格式的文档渲染成html格式。
不过django的模板里会对html做转义,所以还需要修改一下模板。
修改doc.html
给content加上safe过滤器,表示不需要转义,直接显示原始内容。
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Doc - {{ docname }}</title>
<link href="/static/css/highlights/github.css"/></head><body>{{ content | safe }}</body></html>
原文链接:https://www.jianshu.com/p/898ac2bd41e8

随时随地看视频