一个简单的Sitemap模板可以生成sitemap.xml文件. Hugo自动携带了这个模板文件. 不需要用户做任何事情, 除非需要定制 sitemap.xml

Sitemap也是一个Page,因此可以访问所有page variables,可以应用在模板中,还有Sitemap特定的一些变量:

.Sitemap.ChangeFreq
页面变化频率
.Sitemap.Priority
页面优先级别
.Sitemap.Filename
文件名称

如果提供了/layouts/sitemap.xml, Hugo会使用这个模板,替代hugo自带的内部的 sitemap.xml模板.

Sitemap模板

Hugo内建了Sitemap模板m, 不过如果有需要可以提供自己的模板,放置于layouts/sitemap.xml 或者 layouts/_default/sitemap.xml.

对于多语言站点, 我们也创建了Sitemap索引. 可以在layouts/sitemapindex.xml or layouts/_default/sitemapindex.xml提供定制的layout布局.

Hugo的sitemap.xml

下面的模板遵循0.9版本的Sitemap 协议.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" | safeHTML }}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
  {{ range .Data.Pages }}
  <url>
    <loc>{{ .Permalink }}</loc>{{ if not .Lastmod.IsZero }}
    <lastmod>{{ safeHTML ( .Lastmod.Format "2006-01-02T15:04:05-07:00" ) }}</lastmod>{{ end }}{{ with .Sitemap.ChangeFreq }}
    <changefreq>{{ . }}</changefreq>{{ end }}{{ if ge .Sitemap.Priority 0.0 }}
    <priority>{{ .Sitemap.Priority }}</priority>{{ end }}{{ if .IsTranslated }}{{ range .Translations }}
    <xhtml:link
                rel="alternate"
                hreflang="{{ .Lang }}"
                href="{{ .Permalink }}"
                />{{ end }}
    <xhtml:link
                rel="alternate"
                hreflang="{{ .Lang }}"
                href="{{ .Permalink }}"
                />{{ end }}
  </url>
  {{ end }}
</urlset>

Hugo的sitemapindex.xml

下面的实现创建了多语言模式下的Sitemap 索引:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" | safeHTML }}
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	{{ range . }}
	<sitemap>
	   	<loc>{{ .SitemapAbsURL }}</loc>
		{{ if not .LastChange.IsZero }}
	   	<lastmod>{{ .LastChange.Format "2006-01-02T15:04:05-07:00" | safeHTML }}</lastmod>
		{{ end }}
	</sitemap>
	{{ end }}
</sitemapindex>

配置 sitemap.xml

可以在站点配置文件中设置sitemap的<changefreq>, <priority>filename的值

config.
     
1
2
3
4
sitemap:
  changefreq: monthly
  filename: sitemap.xml
  priority: 0.5
1
2
3
4
[sitemap]
  changefreq = "monthly"
  filename = "sitemap.xml"
  priority = 0.5
1
2
3
4
5
6
7
{
   "sitemap": {
      "changefreq": "monthly",
      "filename": "sitemap.xml",
      "priority": 0.5
   }
}

这些相同字段也可以在单独文件的前言设定部分指定,以重载这片内容在呈现时的赋值。