如何在 Blogger 裡放程式碼?

Blogger 裡面預設沒有這個功能,要自己加。網路上教學很多,我參考之後整理出符合自己喜好的方式。

一、步驟

1. 選擇「版面配置→新增小工具」

2. 選擇「HTML/JavaScript」

3. 在「內容」輸入程式碼

<link rel="stylesheet" type="text/css" href="https://jmblog.github.io/color-themes-for-google-code-prettify/themes/tomorrow-night.min.css" />
<style type="text/css">
    pre.prettyprint {
        line-height: 1.5em;
        padding: 2px 10px;
    }
</style>
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>

4. 把小工具拖拉到標頭最上面,並儲存

如何在 Blogger 裡放程式碼? - 把小工具拖拉到標頭

二、使用

切換成 HTML 編輯模式,把程式碼用 <pre class="prettyprint"></pre> 包起來即可,要注意的是程式碼要先 html encode 過。
如何在 Blogger 裡放程式碼? -  使用 html encode
要顯示行數可以在 class 加上 linenums 變成 <pre class="prettyprint linenums"></pre> 。
如果是在文字間則改用 <code class="prettyprint"></code> 才不會斷行。

三、補充說明

我使用 Google Code Prettify,參考文件載入 JavaScript。
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
但由於官方提供的主題我都不是很喜歡,後來發現可以去 Color Themes for Google Code Prettify 選一個喜歡的主題載入。
<link rel="stylesheet" type="text/css" href="https://jmblog.github.io/color-themes-for-google-code-prettify/themes/tomorrow-night.min.css" />
最後再加一點自己客製的 CSS。
<style type="text/css">
    pre.prettyprint {
        line-height: 1.5em;
        padding: 2px 10px;
    }
</style>

留言

張貼留言