Hugo Shortcode 渲染外部代码和文件

Page content

有时在我的文章中会包含代码块(例如,javascript);一个直接的方法是将代码直接复制到相应的markdown文件中。

然而,由于将来可能会更新这段代码,但仍然希望我的博客文章显示最新的版本。 有时在多篇文章中引用同一个代码块,更新的时候就比较麻烦,需要复制粘贴多次。

Hugo shortcode允许把代码作为文本块导入markdown文件,很好的解决了这问题。

创建shortcode code.html

新建code.html 并粘贴如下内容

{{ $file := .Get "file" | readFile }}
{{ $lang := .Get "language" }}
{{ (print "```" $lang "\n" $file "\n```") | markdownify }}

展示code

{{ % code file="/static/js/custom.js" language="js" % }}

custom.js内容的样式如下:

console.log("hello, lockshell");


创建shortcode include.html

有一个更简单的解决方案,新建shortcode(命名为include.html),内容如下,并把它放到layouts/shortcodes文件夹中。

{{ $file := .Get 0 }}
{{ $file | readFile | safeHTML }}  

展示外部文件

在md中引入外部文件:

{{ % include "/static/js/custom.js" %}}

custom.js内容的样式如下:

console.log(“hello, lockshell”);

而/static/js/custom.js的内容也能在文章中正常渲染。