让我们把codepen嵌入到hugo博客中。

长话短说,主要原理使用了hugo自带的shortcodes能力。

步骤

step1 新建shortcode模版

在hugo的root目录下;

mkdir -p layouts/shortcodes && touch layouts/shortcodes/codepen.html && ls -al layouts/shortcodes

step2 创作模版内容

模版内容很强大,不仅能用来简化codepen的插入,也可以定制其他模版用来渲染,这里我们只讨论codepen,以下是我的code:

{{ if .Site.Params.codePenUser }}
  <iframe height="300" scrolling="no" title="code demonstration with codePen" src="//codepen.io/{{ .Site.Params.codepenUser | lower }}/embed/{{ .Get "id" }}/?height=265&theme-id=dark&default-tab=result,result&embed-version=2" frameborder="no" allowtransparency="true" allowfullscreen="true" style="width: 100%;">
    <div>
      <a href="//codepen.io/{{ .Site.Params.codePenUser | lower }}/pen/{{ .Get "id" }}">See the demo on codePen</a>
    </div>
  </iframe>
{{ else }}
  <p class="site-error"><strong>Site error:</strong> The <code>codePenUser</code> param has not been set in <code>config.toml</code></p>
{{ end }}

我们可以直接将上面的代码片段复制,贴到layouts/shortcode/codepen.html

step3 设置codepen用户名

第二步的代码依赖.Site.Params.codePenUser变量获取codepen用户名,因此需要在hugo的config.toml中进行设置,如下图

image.png

这里要注意的是,根据hugo文档codePenUser要放在[parmas]的map之下。

到这里理论上技术性改造已经完成,可以直接使用嵌入的codepen了。

使用

在markdown中写入如下模版引用:

image36731254a98200b7.png

将会解析为

{{< codepen id="GRjZQog" >}}

step2中的脚本可以再增加一个参数,比如username,万一哪天你要引用别人的pen呢?

引入bilibili

shortcode:

<div style="position:relative; padding-bottom:75%; width:100%; height:0">
    <iframe src="//player.bilibili.com/player.html?bvid={{.Get 0}}&amp;page={{.Get 1}}" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true" style="position:absolute; height: 100%; width: 100%;"></iframe>
</div>

使用:

id替换为b站视频的id

{{< bilibili id >}}