2

在Hugo博客中加入代码高亮

 2 years ago
source link: https://blog.xpgreat.com/p/hugo_add_highlight/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

相信自己搭建博客的人中有一大半都是玩代码的,所以代码高亮可以说是博客的必备功能。本文提供一个在基于Hugo的博客上使用highlight.js的代码高亮方案。

  1. highlight.js的官方网站上复制HTML的linkscript标签。例如:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>
  1. 打开themes/yourtheme/layouts/_default目录,打开baseof.html,(可能对不同主题文件和路径会有不同,如果找不到可以试试查找head.htmlheader.html。这个html文件是网页的head部分的模板。在合适的地方粘贴第一步中的代码。

  2. 大功告成。

用```包裹代码块,保险起见,在```后加上语言名字。例如(不包括方括号内):

[START HERE]
```c
int hash(char * str, int length) { // hash function
    int hash = 0;
    for (int i = 0; i < length; i++) {
        hash = ((hash + str[i]) * 31) % MAX_ID; // maximum of ID?
    }
    return hash;
}
```[END HERE]

显示效果如下:

int hash(char * str, int length) { // hash function
    int hash = 0;
    for (int i = 0; i < length; i++) {
        hash = ((hash + str[i]) * 31) % MAX_ID; // maximum of ID?
    }
    return hash;
}
  1. 如果要使用的语言很生僻,链接内的js和css可能无法满足需求,可以添加新的script,比如:https://cdn.bootcss.com/highlight.js/9.12.0/languages/yaml.min.js。或者在highlight.js的官方网站上自定义并下载下来,用本地引用。

  2. 如果需要修改颜色、背景色等样式,可以把css下载下来,修改后本地引用。修改后的css放在themes/yourtheme/static/css里,用href="/css/highlight.css"引用。强烈建议在css里把背景色去除。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK