Hugo Markdown 设置图片大小(通过Image Render Hooks)

笔者用 hugo 搭建了一个个人博客, 源文件是 markdown 格式, 发现并没有通用的设置图片大小的方式. 经过一番搜索, 发现了可以通过 Hugo Image Render Hooks 方式来自定义设置图片大小. 流程跑通后, 整理其方法如下, 希望给读者一些参考.

笔者环境

操作步骤

1. 更新网站配置

笔者用的格式为yaml, 配置文件为: hugo.yaml, 更新配置如下:

goldmark:
  parser:
    attribute:
      block: true
      title: true
    wrapStandAloneImageWithinParagraph: false
  renderHooks:
    image:
      enableDefault: true

更多参考请访问: Configure markup

2. 更新渲染模板

笔者用的主题是自己做的, 所以就直接改在了主题仓库里面. 在博客的相应目录是否能修改成功我没有验证过.

修改文件 layouts/_default/_markup/render-image.html, 增加自定义渲染:

{{- $u := urls.Parse .Destination -}}
{{- $src := $u.String -}}
{{- if not $u.IsAbs -}}
  {{- $path := strings.TrimPrefix "./" $u.Path -}}
  {{- with or (.PageInner.Resources.Get $path) (resources.Get $path) -}}
    {{- $src = .RelPermalink -}}
    {{- with $u.RawQuery -}}
      {{- $src = printf "%s?%s" $src . -}}
    {{- end -}}
    {{- with $u.Fragment -}}
      {{- $src = printf "%s#%s" $src . -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
<figure class="flex flex-col items-center justify-center">
    <img src="{{ $src }}" alt="{{ .PlainText }}"
    {{- with .Title }} title="{{ . }}" {{- end -}}
    {{- with index .Attributes "width" -}} width="{{ . }}" {{- end -}}
    {{- with index .Attributes "height" -}} height="{{ . }}" {{- end -}}
    >
    {{- with index .Attributes "caption" -}}
        <figcaption>{{ . }}</figcaption>
    {{- end -}}
</figure>
{{- /**/ -}}

代码源文件

可以看到我这里的渲染文件支持三个参数:

  1. width: 图片宽度
  2. height: 图片高度
  3. caption: 图片标题

参考: Image Render Hooks.

3. 设置图片 Attribute

![book cover](/images/posts/book-philosophy-of-software-design/cover.jpeg "A Philosophy of Software Design")
{width="300",caption="书籍封面"}

需要注意Attribute需要另起一行并紧跟在图片之后.

效果预览

参考链接

Tags: