继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Django:为模板渲染加入Markdown支持

杨魅力
关注TA
已关注
手记 371
粉丝 57
获赞 264

两种方法

  • 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


打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP