google-code-prettify導入

スポンサーリンク

WordPressの記事上でコードを読みやすく載せるためgoogle-code-prettifyを導入しました。

↓google-code-prettifyを使ったコード表示の例

import sys

class Hoge:
    def __init__(self, x):
        self.x = x

print "aaa"

見ての通り、行番号の表示やシンタックスハイライトが行えます

導入手順

1.
ここからファイルを落とす
(smallは改行やスペースが切り詰めてあるやつです)

2.
適当な場所にアップロード

3.
google-code-prettifyを使いたいページのHTMLにcssとjsの読み込みタグを追加

<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

(パスは適宜変更します)

4.
bodyタグにonload=”prettyPrint()”を追加

<body onload="prettyPrint()">

5.
コードをpreまたはcodeタグで囲み、class=”prettyprint”を指定する

<pre class="prettyprint">
import sys

class Hoge:
    pass
</pre>

メモ

行番号を表示

class指定にlinenumsを追加します

<pre class="prettyprint linenums">

linenums:5というようにして開始行番号を変更することもできます

行番号を全行表示

デフォルトでは5行毎になっている行番号表示を全行に表示するには、prettify.cssの46行目あたりにあるlist-stle-type:noneを削除します
(参考:javascript – How to add line numbers to all lines in Google Prettify? – Stack Overflow

/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { /*list-style-type: none */ } /* ←とりえずコメントアウト */
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background: #eee }
スポンサーリンク
スポンサーリンク
Web
フォローする
Akashic Records
タイトルとURLをコピーしました