返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Django

Django: Adding Markdown Support for Template Rendering

Two methods Django's django-markdown-deux module Python module markdown django-markdown-deux First, you need to install: pip install django-markdown-deux Modify setting.py Add markdown-deux to it INSTALLED_APPS = [ 'markdown-deux', ] Add tags in the template

曦远 (DealiAxy)约 5 分钟
目录3 个章节

Two methods

  • Django's django-markdown-deux module
  • Python module markdown

django-markdown-deux

First, you need to install:

pip install django-markdown-deux

Modify setting.py Add markdown-deux to it

INSTALLED_APPS = [
    'markdown-deux',
]

Add tags in the template After loading the markdown-deux-tags tag, add a filter to the markdown content and it can be parsed into 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>

Rendering with the markdown module

First, install

pip install markdown

Use markdown rendering in views.py

import markdown

def 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)

The markdown module will directly render markdown-formatted documents into html format. However, Django's templates will escape html, so you still need to modify the template a bit.

Modify doc.html Add the safe filter to content, indicating that escaping is not needed and the original content should be displayed directly.

<!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>

_EOF_

Django: Adding Markdown Support for Template Rendering

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

Django项目引入NPM和gulp管理前端资源

前言 之前写了一篇《Asp-Net-Core开发笔记:使用NPM和gulp管理前端静态文件》,现在又来用Django开发项目了,之前我搞了一个Django的快速开发脚手架「DjangoStarter」,正好给升级一下~ 关于npm和gulp我就不多重复了,之前那篇文章都写了,直接上操作 安装依赖 安装依赖的操作跟上一篇文章是一样的,不过我这里直接提供package.json文件,复制到项目根目录里

2022-04-02 · Django · 约 1 分钟

一小时完成后台开发:DjangoRestFramework开发实践

DjangoRestFramework开发实践 在这之前我写过一篇关于Django与Drf快速开发实践的博客,Django快速开发实践:Drf框架和xadmin配置指北,粗略说了一下Drf配置和基本使用,不过里面只是涉及到最基本的CRUD,在正常的后端开发中涉及的诸如认证和权限、消息队列、缓存之类的操作,上一篇博客并没有涉及,这次开发我仔细了看了官方文档的这几个部分,把这部分的功能完善了起来。 D

2021-12-18 · Django · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…