Django+Markdown+Pygments 支持Markdown 实现代码高亮

Markdown部分
  1. 安装markdown pip install markdown
  2. view.py中导入包 from markdown import markdown
  3. 使用markdown()将需要用markdown格式解析的内容(字符串)封装起来。 注:models里面有一个Article类,Article里面有一项是content存储博客内容。

    def detail(request, id):
        try:
            post = Article.objects.get(id=str(id))
            #for markdown test
            post.content = markdown(post.content) 
        except Article.DoesNotExist:
            raise Http404
        return render(request, 'post.html', {'post' : post}) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  4. 在后台编辑博文 
    > ## This is a test. 

    > 1. This is the first list item. 
    > 2. This is the second list item.

  5. 前台显示 {{ post.content | safe}},注意使用了safe过滤器,防止内容在输出前被解析。 
    ps:和这个问题是一个原因,django数据库里Html代码,如何在前台让浏览器正确解析?

Pygments部分
    1. 官网下载最新的版本的Pygments
    2. 使用pip安装下载的包Pygments-2.0.2.tar.gz,敲命令pip install Pygments-2.0.2.tar
    3. 运行如下命令pygmentize -S default -f html -a .codehilite > code.css,在文件夹下会发现生成了code.css文件,将这个css文件加入到你的static文件夹下style里面(随便你放哪里找得到就好)。
    4. 在需要高亮的html文件里面导入刚刚生成的css文件,例如我的是<link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}styles/code.css"/>
    5. 还记得刚刚代码里面的post.content = markdown(post.content) 
      吧,在后面加上['codehilite'],即为post.content = markdown(post.content,['codehilite'])
    6. 刷新前台,显示代码已经高亮。

转载于:https://www.cnblogs.com/jiangqiuju/p/8304202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值