Hugo 静态网站生成器中的 OpenGraph 图像元数据

如何向Hugo添加OpenGraph元数据?

目录

[Opengraph 图像元数据](https://www.glukhov.org/zh-cn/post/2025/07/opengraph-image-metadata-in-hugo/ “Hugo 网站中的 Opengraph 图像元数据) 是元属性 og:image。 基本上,我们希望在我们基于 Hugo 的网站的每一页上正确生成标签 <meta property="og:image" content="https://....jpg">

Hugo 标志和标语

如何包含 OpenGraph 元数据

在您的主题代码中搜索

{{ template "_internal/opengraph.html" . }}

它可能已经包含在内。 如果找不到,您可以尝试自己添加。

  • 创建或从您的主题中复制 layouts/_default/baseof.html
  • 在其中的头部添加:
<head>
  .....
  {{ template "_internal/opengraph.html" . }}

完成了吗?现在使用 hugo 命令生成您的网站,并检查生成的 index.html 文件中的某个页面。

hugo
head -100 public/post/test/index.html

您没有看到 <meta property="og:image"...,对吗?

好的,标准实现中还有一些其他条件。

Hugo 官方文档

https://gohugo.io/templates/embedded/#open-graph

  1. 基本上,您需要在页面的 frontmatter 中指定您希望在元数据中发布的图像,例如
---
title: "我的 Hugo 测试页面标题"
description: "我的 Hugo 测试页面描述"

date: "2025-07-15"
lastmod: "2025-07-15"

tags:
  - Hugo
  - 图像

images:
  - post-cover1.png
  - post-cover2.png
---

但如果您已经有一个包含千页的网站,这可能为时已晚。不用担心,还有另一种方法。

  1. 将图像存储在页面包中,并使用特殊名称。

_internal/opengraph.html 调用 _funcs/get-page-images.html,它会在您的页面包中搜索包含 feature(如 feature.png)的图像文件,如果没有找到特征图像,则会搜索包含 coverthumbnail 的图像文件。

get-page-images.html 的一部分:

{{- $featured := $resources.GetMatch "*feature*" -}}
  {{- if not $featured }}{{ $featured = $resources.GetMatch "{*cover*,*thumbnail*}" }}{{ end -}}
  {{- with $featured }}
    {{- $imgs = $imgs | append (dict
      "Image" .
      "RelPermalink" .RelPermalink
      "Permalink" .Permalink) }}
  {{- end }}
  1. 回退到全局网站参数 - 只会使用第一张图像。

在 hugo.toml 中的某处

[params]
  description = '我的精彩网站'
  images = ['default-feature-image.jpg']

或者如果您使用 hugo.yaml:

params:
  description: '我的精彩网站'
  images:
  - default-feature-image.jpg

您可以在 get-page-images.html 中找到这段代码:

{{- if and (not $imgParams) (not $imgs) }}
  {{- with site.Params.images }}
    {{- $imgParams = first 1 . }}
  {{- end }}
{{- end }}

本网站

正如您所猜测并看到的,本网站也使用了 Hugo。 在这里,我按照标准的 Hugo/MainRoad 方式在页面 frontmatter 中引用了缩略图图像:

thumbnail: this-page-thumbnail.jpg 

但我的缩略图 已经很好地调整了大小 到 235px 的宽度……哦,这不足以作为页面封面图像。其他图像的名称也各不相同……

我以简单的方式进行了修复 - 我只是将默认图像参数添加到了网站配置中。现在,所有在这篇帖子之前的页面都会使用这张小型 Kubernetes 集群的图像作为它们的 opengraph 元数据:

dell usff stack

我可能在未来会做一些更改,比如编写一个自动脚本来更新所有页面的 frontmatter 部分,但目前这已经足够了。

有用的链接