代码语法高亮显示

代码语法高亮显示

最近在做一个自动生成代码的玩意儿,想直接网页显示代码,然没有语法高亮的代码简直丑爆了,然而google-code-prettify让这一切都变得很简单,但是个人感觉加载大段代码还是有点慢慢的

这里直接说怎么玩儿吧

1. 引入需要的js和css

    <link href="http://cdn.bootcss.com/prettify/r298/prettify.css" rel="stylesheet">
    <script src="http://cdn.bootcss.com/prettify/r298/prettify.js"></script>
    <script src="http://cdn.bootcss.com/prettify/r298/run_prettify.js"></script>

2. 在pre节点中添加class标记

<pre class="prettyprint lang-python">

3. pre节点里面放你的代码

<pre class="prettyprint lang-python">  
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.db.utils import IntegrityError
from attendence.decrator import valid_user
from secu.models.User import User
from attendence.models.Employee import Employee

class Adjustment(object):

    @staticmethod
    @valid_user
    def index(request):
        context = {
            'title': 'Adjustment',
        }

        return render(request, 'attendence/Adjustment.html', context)
</pre>

4. 加点自定义的背景和边框

    <style type="text/css">
        pre.prettyprint  
        {  
            border: 2px dashed #888;  
            background: #ddd;  
            margin-bottom: 30px;
        }  
    </style>

5. 效果

6. pre中的prettyprint能自动执行js方法prettyprint,如果需要手动载入的话就在onload里面调用

<script>  
    window.onload = function ()  
    {  
        // Load Prettify  
        prettyPrint();  
    }  
</script> 

7. 不拷贝代码,直接使用CDN库

www.bootcdn.cn/prettify/

8. 默认支持

The comments in prettify.js are authoritative but the lexer should work on a number of languages 
including C and friends, Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, Makefiles, and Rust.

意思就是在没有额外插件的情况下,prettify 就可以支持 python的代码高亮!

如果是其他的语言的话就需要引入相应的js文件,比如go语言,那么就需要lang-go.js

9. 下载地址

google-code-prettify.zip

posted @ 2016-06-03 22:03  CooMark  阅读(1479)  评论(0编辑  收藏  举报