要在文章裡放程式碼,又要它自動上色,Google 出的 Code Prettify 是最省事的方案之一:只要兩個標籤加上一個 class 名稱,它就會自動辨識語言並套用樣式。
<link href="https://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css"
rel="stylesheet" type="text/css"/>
<script src="https://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"
type="text/javascript"></script>
<body onload='prettyPrint()'>
<pre class="prettyprint"> /* source code */ </pre>
就這樣,Prettify 會掃描頁面上所有帶 prettyprint class 的 pre 元素,自動判斷語言並上色。
class="prettyprint lang-html" 或 lang-js、lang-css,可跳過自動偵測,特別適合程式碼片段太短、容易判斷錯誤的情況。linenums:false;要顯示則用 linenums。<body onload>,也可以在 DOM 就緒後自行呼叫 prettyPrint(),避免覆蓋掉其他人掛在 onload 上的處理器。<、>、& 都要寫成 HTML 實體,否則會被瀏覽器當成標籤解析。範例中的 google-code-prettify.googlecode.com 是 Google Code 時期的網址,該平台早已停止服務,這個路徑目前無法使用。實作時請改為引入 npm 上的 google-code-prettify 套件、cdnjs 等 CDN,或將檔案下載後放在自己的專案裡,避免依賴外部服務而導致頁面載入失敗。
若你在寫 Markdown,多數平台(GitHub、GitBook、各種靜態產生器)已內建 highlight.js 或 Prism 這類高亮器,通常不必另外處理。