这是本节的多页打印视图。 点击此处打印.

返回本页常规视图.

函数

1 - 函数快速参考

将以下英文翻译为中文:

Functions Quick Reference

https://gohugo.io/functions/

Go templates are lightweight but extensible. Go itself supplies built-in functions, including comparison operators and other basic tools. These are listed in the Go template documentation. Hugo has added additional functions to the basic template logic.

2 - .AddDate

.AddDate

​ 返回将给定的年数、月数和天数添加到给定的 time.Time 值所得到的时间。

语法

.AddDate YEARS MONTHS DAYS
{{ $d := "2022-01-01" | time.AsTime }}

{{ $d.AddDate 0 0 1 | time.Format "2006-01-02" }} --> 2022-01-02
{{ $d.AddDate 0 1 1 | time.Format "2006-01-02" }} --> 2022-02-02
{{ $d.AddDate 1 1 1 | time.Format "2006-01-02" }} --> 2023-02-02

{{ $d.AddDate -1 -1 -1 | time.Format "2006-01-02" }} --> 2020-11-30

​ 当增加月份或年份时,如果所得日期不存在,Hugo会将最终的 time.Time 值规范化。例如,在1月31日后增加一个月,会得到3月2日或3月3日,具体取决于年份。

​ 参见Go团队的解释

1
2
3
4
5
6
7
8
{{ $d := "2023-01-31" | time.AsTime }}
{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} --> 2023-03-03

{{ $d := "2024-01-31" | time.AsTime }}
{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} --> 2024-03-02

{{ $d := "2024-02-29" | time.AsTime }}
{{ $d.AddDate 1 0 0 | time.Format "2006-01-02" }} --> 2025-03-01

另请参阅

3 - .Format

将以下英文翻译为中文:

.Format

https://gohugo.io/functions/format/

​ 根据 Go 的布局字符串格式化内置的 Hugo 日期 —— .Date.PublishDate.Lastmod

语法

.Format FORMAT

.Format 将格式化在前置元数据中定义的日期值,并可用作以下页面变量的属性:

  • .PublishDate
  • .Date
  • .Lastmod

​ 假设内容文件前置元数据中有一个键值对 date: 2017-03-03 ,可以通过 .Format ,后跟期望输出的布局字符串来将日期处理后再构建:

1
{{ .PublishDate.Format "January 2, 2006" }} => March 3, 2017

​ 要格式化您前置元数据中定义的任何日期字符串表示形式,请参见 dateFormat 函数,它仍将利用下面解释的Go 布局字符串,但使用略有不同的语法。

Go 的布局字符串

​ 模板通过布局字符串格式化您的日期,该字符串指向特定的参考时间:

Mon Jan 2 15:04:05 MST 2006

​ 虽然这可能看起来是任意的,但 MST 的数字值为 07 ,因此使布局字符串成为数字序列。

​ 这里有一个可视化解释直接取自 Go 文档

 Jan 2 15:04:05 2006 MST
=> 1 2  3  4  5    6  -7

Hugo 日期和时间模板参考

​ 以下示例显示布局字符串,后跟渲染的输出。

​ 这些示例在CST中进行了渲染和测试,并且都指向内容文件前置元数据中的同一字段:

date: 2017-03-03T14:15:59-06:00
  • .Date (即通过页面变量进行调用)

    返回2017-03-03 14:15:59 -0600 CST

  • "Monday, January 2, 2006"

    返回Friday, March 3, 2017

  • "Mon Jan 2 2006"

    返回Fri Mar 3 2017

  • "January 2006"

    返回March 2017

  • "2006-01-02"

    返回2017-03-03

  • "Monday"

    返回Friday

  • "02 Jan 06 15:04 MST" (RFC822)

    返回03 Mar 17 14:15 CST

  • "02 Jan 06 15:04 -0700" (RFC822Z)

    返回03 Mar 17 14:15 -0600

  • "Mon, 02 Jan 2006 15:04:05 MST" (RFC1123)

    返回Fri, 03 Mar 2017 14:15:59 CST

  • "Mon, 02 Jan 2006 15:04:05 -0700" (RFC1123Z)

    返回Fri, 03 Mar 2017 14:15:59 -0600

​ 有关更多示例,请参见go文档中的time包

基数和序数缩写

​ 目前不支持拼写出的基数(例如"one",“two"和"three”)。

​ 使用 humanize函数将月份的日期渲染为序数:

1
{{ humanize .Date.Day }} of {{ .Date.Format "January 2006" }}

​ 这将输出:

5th of March 2017

使用 .Local.UTC

​ 与 dateFormat 函数一起使用,您还可以将日期转换为 UTC 或本地时区:

  • {{ dateFormat "02 Jan 06 15:04 MST" .Date.UTC }}

    返回03 Mar 17 20:15 UTC

  • {{ dateFormat "02 Jan 06 15:04 MST" .Date.Local }}

    返回03 Mar 17 14:15 CST

另请参阅

4 - .Get

将以下英文翻译为中文:

.Get

https://gohugo.io/functions/get/

​ 访问简码声明中的位置参数和有序参数。

语法

.Get INDEX
.Get KEY

.Get 是在创建您自己的 简码模板 时专门用于访问传递给它的 位置和命名 参数。当与数字索引一起使用时,它查询位置参数(从 0 开始)。使用字符串键时,它查询命名参数。

​ 当访问不存在的命名或位置参数时,.Get 返回一个空字符串而不是中断构建。这使您可以将 .Getifwithdefaultcond 链接在一起来检查参数是否存在。例如:

1
{{ $quality := default "100" (.Get 1) }}

另请参阅

5 - .GetPage

将以下英文翻译为中文:

.GetPage

https://gohugo.io/functions/getpage/

​ 获取给定 pathPage

语法

.GetPage PATH

.GetPage 返回给定 path 的页面。SitePage 都实现了该方法。如果给定相对路径(即没有前导 / 的路径),Page 变量会尝试查找相对于当前页面的页面。

注意: 在 Hugo 0.45 中我们重新设计和简化了 .GetPage API。在此之前,除了路径,您还需要提供一个 Kind 属性,例如 {{ .Site.GetPage "section" "blog" }}。这仍然可以工作,但是现在是多余的(superfluous)。

1
{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}

​ 当找不到页面时,此方法将返回 nil,因此如果找不到blog章节,则上面的示例不会打印任何内容。

​ 要在blog章节中查找一个常规页面:

1
{{ with .Site.GetPage "/blog/my-post.md" }}{{ .Title }}{{ end }}

​ 由于 Page 还提供了一个 .GetPage 方法,因此上述示例与以下示例相同:

1
2
3
{{ with .Site.GetPage "/blog" }}
{{ with .GetPage "my-post.md" }}{{ .Title }}{{ end }}
{{ end }}

.GetPage 和多语言站点

​ 前面的示例使用了完整的内容文件名来查找帖子。根据您的内容组织方式(文件名中是否有语言代码,例如 my-post.en.md),您可能希望在没有扩展名的情况下进行查找。这将为您获取当前语言版本的页面:

1
{{ with .Site.GetPage "/blog/my-post" }}{{ .Title }}{{ end }}

.GetPage 示例

​ 此代码片段(以局部模板的形式)允许您执行以下操作:

  1. 获取 tags 分类法的索引对象。
  2. 将该对象分配给变量 $t
  3. 按受欢迎程度排序与分类法相关联的条目。
  4. 获取分类法中最受欢迎的两个条目(即分配给内容的两个最受欢迎的标签)。

grab-top-two-tags.html

1
2
3
4
5
6
<ul class="most-popular-tags">
{{ $t := .Site.GetPage "/tags" }}
{{ range first 2 $t.Data.Terms.ByCount }}
    <li>{{ . }}</li>
{{ end }}
</ul>

.GetPage 在页面bundle中

​ 如果通过 .GetPage 检索到的页面是Leaf Bundle,并且您需要获取其中的嵌套page资源,则需要使用 .Resources 中的方法,如Page Resources中所述。

​ 有关示例,请参见Headless Bundle文档。

另请参阅

6 - .HasMenuCurrent

将以下英文翻译为中文:

.HasMenuCurrent

https://gohugo.io/functions/hasmenucurrent/

语法

PAGE.HasMenuCurrent MENU MENUENTRY

.HasMenuCurrentPage 对象中的一个方法,返回一个布尔值。如果 PAGE 是给定 MENU 中 MENUENTRY 的一个子菜单选项中 .Page 的相同对象,则返回true。

​ 如果 MENUENTRY 的.Page是一个 section,则从 Hugo 0.86.0 开始,此方法对该章节的任何后代也返回true。

​ 您可以在 菜单模板 中找到其使用示例。

另请参阅

7 - .IsMenuCurrent

将以下英文翻译为中文:

.IsMenuCurrent

https://gohugo.io/functions/ismenucurrent/

语法

PAGE.IsMenuCurrent MENU MENUENTRY

.IsMenuCurrentPage 对象的一个方法,返回一个 boolean 值。如果 PAGE 是给定 MENU 中 MENUENTRY 中 .Page 的相同对象,则返回true

​ 您可以在 菜单模板 中找到其使用示例。

另请参阅

8 - .Param

将以下英文翻译为中文:

.Param

https://gohugo.io/functions/param/

​ 返回一个页面参数,如果存在站点参数则返回站点参数。

语法

.Param KEY

.Param 方法在 .Page 对象中查找给定的 KEY,并返回对应的值。如果无法在页面参数中找到 KEY,则在站点参数中查找 KEY。如果两个位置都找不到 KEY,则 .Param 方法返回 nil

​ 站点和主题开发人员通常在站点级别设置参数,允许内容作者在页面级别上覆盖这些参数。

​ 例如,要在每个页面上显示目录,但允许作者在需要时隐藏目录:

Configuration

config.

=== “yaml”

``` yaml
params:
  display_toc: true
```

=== “toml”

``` toml
[params]
  display_toc = true
```

=== “json”

``` json
{
   "params": {
      "display_toc": true
   }
}
```

Content

content/example.md

=== “yaml”

``` yaml
---
date: "2023-01-01"
display_toc: false
draft: false
title: Example
---
```

=== “toml”

``` toml
+++
date = 2023-01-01
display_toc = false
draft = false
title = 'Example'
+++
```

=== “json”

``` json
{
   "date": "2023-01-01",
   "display_toc": false,
   "draft": false,
   "title": "Example"
}
```

Template

layouts/_default/single.html

1
2
3
{{ if .Param "display_toc" }}
  {{ .TableOfContents }}
{{ end }}

.Param方法返回与给定KEY关联的值,无论该值是否为真值或假值。如果需要忽略假值,请改用此构造:

layouts/_default/single.html

1
{{ or .Params.foo site.Params.foo }}

另请参阅

9 - .Render

将以下英文翻译为中文:

.Render

https://gohugo.io/functions/render/

​ 应用视图来渲染内容。

语法

.Render LAYOUT

​ 该视图是一种替代布局,应该是一个文件名,指向 内容视图 文档中指定位置之一的模板。

​ 此函数仅适用于 列表上下文 中的单个内容。

​ 例如,下面的示例可以使用位于 /layouts/_default/summary.html 中的内容视图来渲染一篇内容:

1
2
3
{{ range .Pages }}
  {{ .Render "summary" }}
{{ end }}

另请参阅

10 - .RenderString

将以下英文翻译为中文:

.RenderString

https://gohugo.io/functions/renderstring/

​ 将标记渲染为 HTML。

语法

.RenderString MARKUP

.RenderStringPage 上的方法,它使用为该页面定义的内容渲染器(如果选项中未设置)将一些标记渲染为 HTML。

​ 该方法带有一个可选的 map 参数,其中包含以下选项:

  • display (“inline”)

    inline or block. If inline (default), surrounding <p></p> on short snippets will be trimmed.

    inlineblock 。如果是 inline (默认值),则会在简码片段周围修剪 <p></p>

  • markup (defaults to the Page’s markup)

    请参见内容格式列表中的标识符。

以下是一些示例:

1
2
3
4
5
{{ $optBlock := dict "display" "block" }}
{{ $optOrg := dict "markup" "org" }}
{{ "**Bold Markdown**" | $p.RenderString }}
{{ "**Bold Block Markdown**" | $p.RenderString  $optBlock }}
{{ "/italic org mode/" | $p.RenderString  $optOrg }}

自 v0.93.0 开始使用 注意markdownify 使用此函数以支持 Render Hooks

另请参阅

11 - .Scratch

将以下英文翻译为中文:

.Scratch

https://gohugo.io/functions/scratch/

​ 该函数用作 “草稿本”,用于存储和操作数据。

​ Scratch 是 Hugo 的一个功能,旨在方便地在 Go 模板中操纵数据。它是一个 Page 或 简码方法,其结果数据将被附加到给定的上下文中,或者它可以作为存储在变量中的唯一实例。

​ 请注意,Scratch 最初是作为一个解决方案创建的,以解决影响 0.48 版本之前的 Hugo 的Go 模板作用域限制问题。有关.Scratch和上下文用例的详细分析,请参阅这篇博客文章

带有上下文的 .Scratch vs. 本地的 newScratch

​ 自 Hugo 0.43 起,有两种使用 Scratch 的不同方式:

页面的 .Scratch

.Scratch 作为Page 方法或 简码方法可用,并将“草稿”数据附加到给定页面上。使用 .Scratch 必须要在 Page 或 简码上下文中。

1
2
3
4
{{ .Scratch.Set "greeting" "bonjour" }}
{{ range .Pages }}
  {{ .Scratch.Set "greeting" (print "bonjour" .Title) }}
{{ end }}

本地的 newScratch

​ 使用 newScratch 函数,可以将 Scratch 实例分配给任何变量。 在这种情况下,不需要Page 或 简码上下文,而 Scratch 的作用域仅为本地。以下方法可以从已分配 Scratch 实例的变量中使用:

1
2
{{ $data := newScratch }}
{{ $data.Set "greeting" "hola" }}

方法

​ Scratch 具有以下方法:

​ 请注意,以下示例假设已在 $scratch 中存储了 本地 Scratch 实例

.Set

​ 设置给定键的值。

1
{{ $scratch.Set "greeting" "Hello" }}

.Get

​ 获取给定键的值。

1
2
3
{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Get "greeting" }} > Hello

.Add

​ 将给定值添加到给定键的现有值中。

​ 对于单个值,Add接受支持 Go 的 + 运算符的值。如果某个键的第一个 Add 是一个数组或切片,则后续添加的内容将追加到该列表中。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{{ $scratch.Add "greetings" "Hello" }}
{{ $scratch.Add "greetings" "Welcome" }}
----
{{ $scratch.Get "greetings" }} > HelloWelcome
{{ $scratch.Add "total" 3 }}
{{ $scratch.Add "total" 7 }}
----
{{ $scratch.Get "total" }} > 10
{{ $scratch.Add "greetings" (slice "Hello") }}
{{ $scratch.Add "greetings" (slice "Welcome" "Cheers") }}
----
{{ $scratch.Get "greetings" }} > []interface {}{"Hello", "Welcome", "Cheers"}

.SetInMap

Takes a key, mapKey and value and adds a map of mapKey and value to the given key.

​ 接收一个 keymapKeyvalue ,并将 mapKeyvalue 的映射添加到给定的 key 中。

1
2
3
4
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.Get "greetings" }} > map[french:Bonjour english:Hello]

.DeleteInMap

Takes a key and mapKey and removes the map of mapKey from the given key.

​ 接收一个 keymapKey ,并从给定的 key 中删除 mapKey 的映射。

1
2
3
4
5
6
{{ .Scratch.SetInMap "greetings" "english" "Hello" }}
{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ .Scratch.DeleteInMap "greetings" "english" }}
----
{{ .Scratch.Get "greetings" }} > map[french:Bonjour]

.GetSortedMapValues

Return an array of values from key sorted by mapKey.

​ 按 mapKey 排序,返回 key 中的值数组。

1
2
3
4
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.GetSortedMapValues "greetings" }} > [Hello Bonjour]

.Delete

Remove the given key.

​ 删除给定的键。

1
2
3
{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Delete "greeting" }}

.Values

Return the raw backing map. Note that you should only use this method on the locally scoped Scratch instances you obtain via newScratch, not .Page.Scratch etc., as that will lead to concurrency issues.

​ 返回原始的后备映射。注意,只应在通过 newScratch 获得的局部范围的Scratch实例上使用此方法,而不是 .Page.Scratch 等,因为会导致并发问题。

另请参阅

12 - .Store

将以下英文翻译为中文:

.Store

https://gohugo.io/functions/store/

Returns a Scratch that is not reset on server rebuilds.

The .Store method on .Page returns a Scratch to store and manipulate data. In contrast to the .Scratch method, this Scratch is not reset on server rebuilds.

Methods

.Set

Sets the value of a given key.

1
{{ .Store.Set "greeting" "Hello" }}

.Get

Gets the value of a given key.

1
2
3
{{ .Store.Set "greeting" "Hello" }}

{{ .Store.Get "greeting" }} → Hello

.Add

Adds a given value to existing value(s) of the given key.

For single values, Add accepts values that support Go’s + operator. If the first Add for a key is an array or slice, the following adds will be appended to that list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{{ .Store.Add "greetings" "Hello" }}
{{ .Store.Add "greetings" "Welcome" }}

{{ .Store.Get "greetings" }} → HelloWelcome
{{ .Store.Add "total" 3 }}
{{ .Store.Add "total" 7 }}

{{ .Store.Get "total" }} → 10
{{ .Store.Add "greetings" (slice "Hello") }}
{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }}

{{ .Store.Get "greetings" }} → []interface {}{"Hello", "Welcome", "Cheers"}

.SetInMap

Takes a key, mapKey and value and adds a map of mapKey and value to the given key.

1
2
3
4
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}

{{ .Store.Get "greetings" }} → map[french:Bonjour english:Hello]

.DeleteInMap

Takes a key and mapKey and removes the map of mapKey from the given key.

1
2
3
4
5
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.DeleteInMap "greetings" "english" }}

{{ .Store.Get "greetings" }} → map[french:Bonjour]

.GetSortedMapValues

Returns an array of values from key sorted by mapKey.

1
2
3
4
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}

{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour]

.Delete

Removes the given key.

1
2
3
{{ .Store.Set "greeting" "Hello" }}

{{ .Store.Delete "greeting" }}

另请参阅

13 - .Unix

将以下英文翻译为中文:

.Unix

https://gohugo.io/functions/unix/

Converts a time.Time value to the number of seconds elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

语法

.Unix
.UnixMilli
.UnixMicro
.UnixNano

The Milli, Micro, and Nano variants return the number of milliseconds, microseconds, and nanoseconds (respectively) elapsed since the Unix epoch.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
.Date.Unix        --> 1637259694
.ExpiryDate.Unix  --> 1672559999
.Lastmod.Unix     --> 1637361786
.PublishDate.Unix --> 1637421261

("1970-01-01T00:00:00-00:00" | time.AsTime).Unix --> 0
("1970-01-01T00:00:42-00:00" | time.AsTime).Unix --> 42
("1970-04-11T01:48:29-08:00" | time.AsTime).Unix --> 8675309
("2026-05-02T20:09:31-07:00" | time.AsTime).Unix --> 1777777771

now.Unix      --> 1637447841
now.UnixMilli --> 1637447841347
now.UnixMicro --> 1637447841347378
now.UnixNano  --> 1637447841347378799

另请参阅

14 - absLangURL

将以下英文翻译为中文:

absLangURL

https://gohugo.io/functions/abslangurl/

Returns an absolute URL with a language prefix, if any.

语法

absLangURL INPUT

Use this function with both monolingual and multilingual configurations. The URL returned by this function depends on:

  • Whether the input begins with a slash
  • The baseURL in site configuration
  • The language prefix, if any

In examples that follow, the project is multilingual with content in both Español (es) and English (en). The default language is Español. The returned values are from the English site.

Input does not begin with a slash

If the input does not begin with a slash, the resulting URL will be correct regardless of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ absLangURL "" }}           →   https://example.org/en/
{{ absLangURL "articles" }}   →   https://example.org/en/articles
{{ absLangURL "style.css" }}  →   https://example.org/en/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ absLangURL "" }}           →   https://example.org/docs/en/
{{ absLangURL "articles" }}   →   https://example.org/docs/en/articles
{{ absLangURL "style.css" }}  →   https://example.org/docs/en/style.css

Input begins with a slash

If the input begins with a slash, the resulting URL will be incorrect when the baseURL includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ absLangURL "/" }}          →   https://example.org/en/
{{ absLangURL "/articles" }}  →   https://example.org/en/articles
{{ absLangURL "/style.css" }} →   https://example.org/en/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ absLangURL "/" }}          →   https://example.org/en/
{{ absLangURL "/articles" }}  →   https://example.org/en/articles
{{ absLangURL "/style.css" }} →   https://example.org/en/style.css

The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.

另请参阅

15 - absURL

将以下英文翻译为中文:

absURL

https://gohugo.io/functions/absurl/

Returns an absolute URL.

语法

absURL INPUT

With multilingual configurations, use the absLangURL function instead. The URL returned by this function depends on:

  • Whether the input begins with a slash
  • The baseURL in site configuration

Input does not begin with a slash

If the input does not begin with a slash, the resulting URL will be correct regardless of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ absURL "" }}           →   https://example.org/
{{ absURL "articles" }}   →   https://example.org/articles
{{ absURL "style.css" }}  →   https://example.org/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ absURL "" }}           →   https://example.org/docs/
{{ absURL "articles" }}   →   https://example.org/docs/articles
{{ absURL "style.css" }}  →   https://example.org/docs/style.css

Input begins with a slash

If the input begins with a slash, the resulting URL will be incorrect when the baseURL includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ absURL "/" }}          →   https://example.org/
{{ absURL "/articles" }}  →   https://example.org/articles
{{ absURL "/style.css" }} →   https://example.org/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ absURL "/" }}          →   https://example.org/
{{ absURL "/articles" }}  →   https://example.org/articles
{{ absURL "/style.css" }} →   https://example.org/style.css

The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.

另请参阅

16 - after

将以下英文翻译为中文:

after

https://gohugo.io/functions/after/

after slices an array to only the items after the Nth item.

语法

after INDEX COLLECTION

The following shows after being used in conjunction with the slice function:

1
2
3
4
5
{{ $data := slice "one" "two" "three" "four" }}
{{ range after 2 $data }}
    {{ . }}
{{ end }}
→ ["three", "four"]

Example of after with first: 2nd–4th Most Recent Articles

You can use after in combination with the first function and Hugo’s powerful sorting methods. Let’s assume you have a list page at example.com/articles. You have 10 articles, but you want your templating for the list/section page to show only two rows:

  1. The top row is titled “Featured” and shows only the most recently published article (i.e. by publishdate in the content files’ front matter).
  2. The second row is titled “Recent Articles” and shows only the 2nd- to 4th-most recently published articles.

layouts/section/articles.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{{ define "main" }}
<section class="row featured-article">
  <h2>Featured Article</h2>
  {{ range first 1 .Pages.ByPublishDate.Reverse }}
  <header>
      <h3><a href="{{ . Permalink }}">{{ .Title }}</a></h3>
  </header>
  <p>{{ .Description }}</p>
{{ end }}
</section>
<div class="row recent-articles">
  <h2>Recent Articles</h2>
  {{ range first 3 (after 1 .Pages.ByPublishDate.Reverse) }}
    <section class="recent-article">
      <header>
          <h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3>
      </header>
      <p>{{ .Description }}</p>
    </section>
  {{ end }}
</div>
{{ end }}

另请参阅

17 - anchorize

将以下英文翻译为中文:

anchorize

https://gohugo.io/functions/anchorize/

Takes a string and sanitizes it the same way as the defaultMarkdownHandler does for markdown headers.

语法

anchorize INPUT

If Goldmark is set as defaultMarkdownHandler, the sanitizing logic adheres to the setting markup.goldmark.parser.autoHeadingIDType.

Since the defaultMarkdownHandler and this template function use the same sanitizing logic, you can use the latter to determine the ID of a header for linking with anchor tags.

1
2
3
4
5
6
{{ anchorize "This is a header" }} --> "this-is-a-header"
{{ anchorize "This is also    a header" }} --> "this-is-also----a-header"
{{ anchorize "main.go" }} --> "maingo"
{{ anchorize "Article 123" }} --> "article-123"
{{ anchorize "<- Let's try this, shall we?" }} --> "--lets-try-this-shall-we"
{{ anchorize "Hello, 世界" }} --> "hello-世界"

另请参阅

18 - append

将以下英文翻译为中文:

append

https://gohugo.io/functions/append/

append appends one or more values to a slice and returns the resulting slice.

语法

COLLECTION | append VALUE [VALUE]...
COLLECTION | append COLLECTION

An example appending single values:

1
2
3
{{ $s := slice "a" "b" "c" }}
{{ $s = $s | append "d" "e" }}
{{/* $s now contains a []string with elements "a", "b", "c", "d", and "e" */}}

The same example appending a slice to a slice:

1
2
{{ $s := slice "a" "b" "c" }}
{{ $s = $s | append (slice "d" "e") }}

The append function works for all types, including Pages.

另请参阅

19 - apply

将以下英文翻译为中文:

apply

https://gohugo.io/functions/apply/

Given a map, array, or slice, apply returns a new slice with a function applied over it.

语法

apply COLLECTION FUNCTION [PARAM...]

apply expects at least three parameters, depending on the function being applied.

  1. The first parameter is the sequence to operate on.
  2. The second parameter is the name of the function as a string, which must be the name of a valid Hugo function.
  3. After that, the parameters to the applied function are provided, with the string "." standing in for each element of the sequence the function is to be applied against.

Here is an example of a content file with names: as a front matter field:

content/example.md

=== “yaml”

``` yaml
---
names:
- Derek Perkins
- Joe Bergevin
- Tanner Linsley
title: Example
---
```

=== “toml”

``` toml
+++
names = ['Derek Perkins', 'Joe Bergevin', 'Tanner Linsley']
title = 'Example'
+++
```

=== “json”

``` json
{
   "names": [
      "Derek Perkins",
      "Joe Bergevin",
      "Tanner Linsley"
   ],
   "title": "Example"
}
```

You can then use apply as follows:

1
{{ apply .Params.names "urlize" "." }}

Which will result in the following:

"derek-perkins", "joe-bergevin", "tanner-linsley"

This is roughly equivalent to using the following with range:

1
{{ range .Params.names }}{{ . | urlize }}{{ end }}

However, it is not possible to provide the output of a range to the delimit function, so you need to apply it.

If you have post-tag-list.html and post-tag-link.html as partials, you could use the following snippets, respectively:

layouts/partials/post-tag-list.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{{ with .Params.tags }}
  <div class="tags-list">
    Tags:
    {{ $len := len . }}
    {{ if eq $len 1 }}
      {{ partial "post-tag-link.html" (index . 0) }}
    {{ else }}
      {{ $last := sub $len 1 }}
      {{ range first $last . }}
        {{ partial "post-tag-link.html" . }},
      {{ end }}
      {{ partial "post-tag-link.html" (index . $last) }}
    {{ end }}
  </div>
{{ end }}

layouts/partials/post-tag-link.html

1
<a class="post-tag post-tag-{{ . | urlize }}" href="/tags/{{ . | urlize }}">{{ . }}</a>

This works, but the complexity of post-tag-list.html is fairly high. The Hugo template needs to perform special behavior for the case where there’s only one tag, and it has to treat the last tag as special. Additionally, the tag list will be rendered something like Tags: tag1 , tag2 , tag3 because of the way that the HTML is generated and then interpreted by a browser.

This first version of layouts/partials/post-tag-list.html separates all of the operations for ease of reading. The combined and DRYer version is shown next:

1
2
3
4
5
6
7
8
9
{{ with .Params.tags }}
  <div class="tags-list">
    Tags:
    {{ $sort := sort . }}
    {{ $links := apply $sort "partial" "post-tag-link.html" "." }}
    {{ $clean := apply $links "chomp" "." }}
    {{ delimit $clean ", " }}
  </div>
{{ end }}

Now in the completed version, you can sort the tags, convert the tags to links with layouts/partials/post-tag-link.html, chomp off stray newlines, and join the tags together in a delimited list for presentation. Here is an even DRYer version of the preceding example:

layouts/partials/post-tag-list.html

1
2
3
4
5
6
{{ with .Params.tags }}
  <div class="tags-list">
    Tags:
    {{ delimit (apply (apply (sort .) "partial" "post-tag-link.html" ".") "chomp" ".") ", " }}
  </div>
{{ end }}

apply does not work when receiving the sequence as an argument through a pipeline.

20 - base64

将以下英文翻译为中文:

base64

https://gohugo.io/functions/base64/

base64Encode and base64Decode let you easily decode content with a base64 encoding and vice versa through pipes.

语法

base64Decode INPUT
base64Encode INPUT
{{ "Hugo" | base64Encode }} → "SHVnbw=="
{{ "SHVnbw==" | base64Decode }} → "Hugo"

base64 with APIs

Using base64 to decode and encode becomes really powerful if we have to handle responses from APIs.

1
2
{{ $resp := getJSON "https://api.github.com/repos/gohugoio/hugo/readme" }}
{{ $resp.content | base64Decode | markdownify }}

The response of the GitHub API contains the base64-encoded version of the README.md in the Hugo repository. Now we can decode it and parse the Markdown. The final output will look similar to the rendered version on GitHub.

21 - chomp

将以下英文翻译为中文:

chomp

https://gohugo.io/functions/chomp/

Removes any trailing newline characters.

语法

chomp INPUT
strings.Chomp INPUT

Useful in a pipeline to remove newlines added by other processing (e.g., markdownify).

1
{{ chomp "<p>Blockhead</p>\n" }} → "<p>Blockhead</p>"

22 - complement

将以下英文翻译为中文:

complement

https://gohugo.io/functions/complement/

Returns the elements of the last collection that are not in any of the others.

语法

complement COLLECTION [COLLECTION]...
collections.Complement COLLECTION [COLLECTION]...

To find the elements within $c3 that do not exist in $c1 or $c2:

1
2
3
4
5
{{ $c1 := slice 3 }}
{{ $c2 := slice 4 5 }}
{{ $c3 := slice 1 2 3 4 5 }}

{{ complement $c1 $c2 $c3 }} → [1 2]

Make your code simpler to understand by using a chained pipeline:

1
{{ $c3 | complement $c1 $c2 }} → [1 2]

You can also use the complement function with page collections. Let’s say your site has five content types:

1
2
3
4
5
6
content/
├── blog/
├── books/
├── faqs/
├── films/
└── songs/

To list everything except blog articles (blog) and frequently asked questions (faqs):

1
2
3
4
5
{{ $blog := where site.RegularPages "Type" "blog" }}
{{ $faqs := where site.RegularPages "Type" "faqs" }}
{{ range site.RegularPages | complement $blog $faqs }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}

Although the example above demonstrates the complement function, you could use the where function as well:

1
2
3
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}

In this example we use the complement function to remove stop words from a sentence:

1
2
3
4
5
{{ $text := "The quick brown fox jumps over the lazy dog" }}
{{ $stopWords := slice "a" "an" "in" "over" "the" "under" }}
{{ $filtered := split $text " " | complement $stopWords }}

{{ delimit $filtered " " }} → The quick brown fox jumps lazy dog

另请参阅

23 - cond

将以下英文翻译为中文:

cond

https://gohugo.io/functions/cond/

Return one of two arguments, depending on the value of a third argument.

语法

cond CONTROL VAR1 VAR2

cond returns VAR1 if CONTROL is true, or VAR2 if it is not.

Example:

1
{{ cond (eq (len $geese) 1) "goose" "geese" }}

Would emit “goose” if the $geese array has exactly 1 item, or “geese” otherwise.

Whenever you use a cond function, both variable expressions are always evaluated. This means that a usage like cond false (div 1 0) 27 will throw an error because div 1 0 will be evaluated even though the condition is false.

In other words, the cond function does not provide short-circuit evaluation and does not work like a normal ternary operator that will pass over the first expression if the condition returns false.

24 - countrunes

将以下英文翻译为中文:

countrunes

https://gohugo.io/functions/countrunes/

Determines the number of runes in a string excluding any whitespace.

语法

countrunes INPUT
strings.CountRunes INPUT

In contrast with countwords function, which counts every word in a string, the countrunes function determines the number of runes in the content and excludes any whitespace. This has specific utility if you are dealing with CJK-like languages.

1
2
{{ "Hello, 世界" | countrunes }}
<!-- outputs a content length of 8 runes. -->

另请参阅

25 - countwords

将以下英文翻译为中文:

countwords

https://gohugo.io/functions/countwords/

Counts the number of words in a string.

语法

countwords INPUT

The template function works similar to the .WordCount page variable.

1
2
{{ "Hugo is a static site generator." | countwords }}
<!-- outputs a content length of 6 words.  -->

另请参阅

26 - crypto.FNV32a

将以下英文翻译为中文:

crypto.FNV32a

https://gohugo.io/functions/crypto.fnv32a/

Returns the FNV (Fowler–Noll–Vo) 32 bit hash of a given string.

语法

crypto.FNV32a STRING

This function calculates the 32 bit FNV1a hash of a given string according to the specification:

{{ crypto.FNV32a "Hello world" }} → 1498229191

27 - default

将以下英文翻译为中文:

default

https://gohugo.io/functions/default/

default函数用于当第一个值未被设置时,返回可以被返回的默认值。

语法

default DEFAULT INPUT

default函数检查给定值是否被设置,如果没有被设置,则返回默认值。在此上下文中,“设置”意味着不同的事情,具体取决于数据类型:

  • 对于数字类型和时间类型,为非零值
  • 对于字符串、数组、切片和映射,为非零长度
  • 对于布尔或结构体值,为任何值
  • 对于任何其他类型,为非nil值

default函数示例引用以下内容页面:

content/posts/default-function-example.md

1
2
3
4
5
6
7
8
---
title: Sane Defaults
seo_title:
date: 2017-02-18
font:
oldparam: The default function helps make your templating DRYer.
newparam:
---

default可以以多种方式编写:

1
2
{{ .Params.font | default "Roboto" }}
{{ default "Roboto" .Params.font }}

​ 上述两个 default函数调用都返回Roboto

​ 但是,default值不需要像上面的例子一样被硬编码。default值可以是变量或直接使用点符号从前置元数据中提取:

1
2
{{ $old := .Params.oldparam }}
<p>{{ .Params.newparam | default $old }}</p>

它将返回:

1
<p>The default function helps make your templating DRYer.</p>

然后使用点符号:

1
<title>{{ .Params.seo_title | default .Title }}</title>

它将返回:

1
<title>Sane Defaults</title>

​ 以下内容具有等效的返回值,但default更为简洁。这演示了default的实用性:

使用if:

1
2
<title>{{ if .Params.seo_title }}{{ .Params.seo_title }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults

使用with:

1
2
<title>{{ with .Params.seo_title }}{{ . }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults

28 - delimit

将以下英文翻译为中文:

delimit

https://gohugo.io/functions/delimit/

Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.

语法

delimit COLLECTION DELIMITER [LAST]

Delimit a slice:

1
2
3
{{ $s := slice "b" "a" "c" }}
{{ delimit $s ", " }} → "b, a, c"
{{ delimit $s ", " " and "}} → "b, a and c"

Delimit a map:

The delimit function sorts maps by key, returning the values.

1
2
3
{{ $m := dict "b" 2 "a" 1 "c" 3 }}
{{ delimit $m ", " }} → "1, 2, 3"
{{ delimit $m ", " " and "}} → "1, 2 and 3"

另请参阅

29 - dict

将以下英文翻译为中文:

dict

https://gohugo.io/functions/dict/

Creates a dictionary from a list of key and value pairs.

语法

dict KEY VALUE [KEY VALUE]...

dict is especially useful for passing more than one value to a partial template.

Note that the key can be either a string or a string slice. The latter is useful to create a deeply nested structure, e.g.:

1
{{ $m := dict (slice "a" "b" "c") "value" }}

Example: Using dict to pass multiple values to a partial

The partial below creates an SVG and expects fill, height and width from the caller:

Partial definition

layouts/partials/svgs/external-links.svg

1
2
3
4
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
fill="{{ .fill }}" width="{{ .width }}" height="{{ .height }}" viewBox="0 0 32 32" aria-label="External Link">
<path d="M25.152 16.576v5.696q0 2.144-1.504 3.648t-3.648 1.504h-14.848q-2.144 0-3.648-1.504t-1.504-3.648v-14.848q0-2.112 1.504-3.616t3.648-1.536h12.576q0.224 0 0.384 0.16t0.16 0.416v1.152q0 0.256-0.16 0.416t-0.384 0.16h-12.576q-1.184 0-2.016 0.832t-0.864 2.016v14.848q0 1.184 0.864 2.016t2.016 0.864h14.848q1.184 0 2.016-0.864t0.832-2.016v-5.696q0-0.256 0.16-0.416t0.416-0.16h1.152q0.256 0 0.416 0.16t0.16 0.416zM32 1.152v9.12q0 0.48-0.352 0.8t-0.8 0.352-0.8-0.352l-3.136-3.136-11.648 11.648q-0.16 0.192-0.416 0.192t-0.384-0.192l-2.048-2.048q-0.192-0.16-0.192-0.384t0.192-0.416l11.648-11.648-3.136-3.136q-0.352-0.352-0.352-0.8t0.352-0.8 0.8-0.352h9.12q0.48 0 0.8 0.352t0.352 0.8z"></path>
</svg>

Partial call

The fill, height and width values can be stored in one object with dict and passed to the partial:

layouts/_default/list.html

1
{{ partial "svgs/external-links.svg" (dict "fill" "#01589B" "width" 10 "height" 20 ) }}

另请参阅

30 - duration

将以下英文翻译为中文:

duration

https://gohugo.io/functions/duration/

Returns a time.Duration structure, using the given time unit and duration number.

语法

duration TIME_UNIT DURATION_NUMBER

time.Duration converts a given number into a time.Duration structure so you can access its fields. E.g. you can perform time operations on the returned time.Duration value:

{{ printf "There are %.0f seconds in one day." (duration "hour" 24).Seconds }}
<!-- Output: There are 86400 seconds in one day. -->

Make your code simpler to understand by using a chained pipeline:

{{ mul 7.75 60 | duration "minute" }} → 7h45m0s
{{ mul 120 60 | mul 1000 | duration "millisecond" }} → 2h0m0s

You have to specify a time unit for the number given to the function. Valid time units are:

DurationValid time units
hourshour, h
minutesminute, m
secondssecond, s
millisecondsmillisecond, ms
microsecondsmicrosecond, us, µs
nanosecondsnanosecond, ns

31 - echoParam

将以下英文翻译为中文:

echoParam

https://gohugo.io/functions/echoparam/

Prints a parameter if it is set.

语法

echoParam DICTIONARY KEY
{{ echoParam .Params "project_url" }}

32 - emojify

将以下英文翻译为中文:

emojify

https://gohugo.io/functions/emojify/

Runs a string through the Emoji emoticons processor.

语法

emojify INPUT

emojify runs a passed string through the Emoji emoticons processor.

See the Emoji cheat sheet for available emoticons.

The emojify function can be called in your templates but not directly in your content files by default. For emojis in content files, set enableEmoji to true in your site’s configuration. Then you can write emoji shorthand directly into your content files; e.g. I :heart: Hugo!:

I ❤️ Hugo!

另请参阅

33 - eq

将以下英文翻译为中文:

eq

https://gohugo.io/functions/eq/

Returns the boolean truth of arg1 == arg2.

语法

eq ARG1 ARG2
{{ if eq .Section "blog" }}current{{ end }}

另请参阅

34 - errorf 和 warnf

将以下英文翻译为中文:

errorf and warnf

https://gohugo.io/functions/errorf/

Log ERROR or WARNING from the templates.

语法

errorf FORMAT INPUT

errorf or warnf will evaluate a format string, then output the result to the ERROR or WARNING log (and only once per error message to avoid flooding the log).

Any ERROR will also cause the build to fail (the hugo command will exit -1).

Both functions return an empty string, so the messages are only printed to the console.

1
2
{{ errorf "Failed to handle page %q" .Path }}
{{ warnf "You should update the shortcodes in %q" .Path }}

Note that errorf, erroridf, and warnf support all the formatting verbs of the fmt package.

Suppress errors

Sometimes it may make sense to let the user suppress an ERROR and make the build succeed.

You can do this by using the erroridf function. This functions takes an error ID as the first argument.

1
{{ erroridf "my-custom-error" "You should consider fixing this." }}

This will produce:

ERROR 2021/06/07 17:47:38 You should consider fixing this.
If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site config:
ignoreErrors = ["my-custom-error"]

另请参阅

35 - fileExists

将以下英文翻译为中文:

fileExists

https://gohugo.io/functions/fileexists/

Checks for file or directory existence.

语法

os.FileExists PATH
fileExists PATH

The os.FileExists function attempts to resolve the path relative to the root of your project directory. If a matching file or directory is not found, it will attempt to resolve the path relative to the contentDir. A leading path separator (/) is optional.

With this directory structure:

1
2
3
4
5
6
content/
├── about.md
├── contact.md
└── news/
    ├── article-1.md
    └── article-2.md

The function returns these values:

1
2
3
4
5
6
7
{{ os.FileExists "content" }} --> true
{{ os.FileExists "content/news" }} --> true
{{ os.FileExists "content/news/article-1" }} --> false
{{ os.FileExists "content/news/article-1.md" }} --> true
{{ os.FileExists "news" }} --> true
{{ os.FileExists "news/article-1" }} --> false
{{ os.FileExists "news/article-1.md" }} --> true

36 - findRE

将以下英文翻译为中文:

findRE

https://gohugo.io/functions/findre/

Returns a slice of strings that match the regular expression.

语法

findRE PATTERN INPUT [LIMIT]
strings.FindRE PATTERN INPUT [LIMIT]

By default, findRE finds all matches. You can limit the number of matches with an optional LIMIT parameter.

When specifying the regular expression, use a raw string literal (backticks) instead of an interpreted string literal (double quotes) to simplify the syntax. With an interpreted string literal you must escape backslashes.

This function uses the RE2 regular expression library. See the RE2 syntax documentation for details. Note that the RE2 \C escape sequence is not supported.

The RE2 syntax is a subset of that accepted by PCRE, roughly speaking, and with various caveats.

This example returns a slice of all second level headings (h2 elements) within the rendered .Content:

1
{{ findRE `(?s)<h2.*?>.*?</h2>` .Content }}

The s flag causes . to match \n as well, allowing us to find an h2 element that contains newlines.

To limit the number of matches to one:

1
{{ findRE `(?s)<h2.*?>.*?</h2>` .Content 1 }}

You can write and test your regular expression using regex101.com. Be sure to select the Go flavor before you begin.

另请参阅

37 - findRESubmatch

将以下英文翻译为中文:

findRESubmatch

https://gohugo.io/functions/findresubmatch/

Returns a slice of all successive matches of the regular expression. Each element is a slice of strings holding the text of the leftmost match of the regular expression and the matches, if any, of its subexpressions.

语法

findRESubmatch PATTERN INPUT [LIMIT]
strings.FindRESubmatch PATTERN INPUT [LIMIT]

By default, findRESubmatch finds all matches. You can limit the number of matches with an optional LIMIT parameter. A return value of nil indicates no match.

When specifying the regular expression, use a raw string literal (backticks) instead of an interpreted string literal (double quotes) to simplify the syntax. With an interpreted string literal you must escape backslashes.

This function uses the RE2 regular expression library. See the RE2 syntax documentation for details. Note that the RE2 \C escape sequence is not supported.

The RE2 syntax is a subset of that accepted by PCRE, roughly speaking, and with various caveats.

Demonstrative examples

1
2
3
4
5
{{ findRESubmatch `a(x*)b` "-ab-" }} → [["ab" ""]]
{{ findRESubmatch `a(x*)b` "-axxb-" }} → [["axxb" "xx"]]
{{ findRESubmatch `a(x*)b` "-ab-axb-" }} → [["ab" ""] ["axb" "x"]]
{{ findRESubmatch `a(x*)b` "-axxb-ab-" }} → [["axxb" "xx"] ["ab" ""]]
{{ findRESubmatch `a(x*)b` "-axxb-ab-" 1 }} → [["axxb" "xx"]]

Practical example

This markdown:

1
2
- [Example](https://example.org)
- [Hugo](https://gohugo.io)

Produces this HTML:

1
2
3
4
<ul>
  <li><a href="https://example.org">Example</a></li>
  <li><a href="https://gohugo.io">Hugo</a></li>
</ul>

To match the anchor elements, capturing the link destination and text:

1
2
{{ $regex := `<a\s*href="(.+?)">(.+?)</a>` }}
{{ $matches := findRESubmatch $regex .Content }}

Viewed as JSON, the data structure of $matches in the code above is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[
  [
    "<a href=\"https://example.org\"></a>Example</a>",
    "https://example.org",
    "Example"
  ],
  [
    "<a href=\"https://gohugo.io\">Hugo</a>",
    "https://gohugo.io",
    "Hugo"
  ]
]

To render the href attributes:

1
2
3
{{ range $matches }}
  {{ index . 1 }}
{{ end }}

Result:

1
2
https://example.org
https://gohugo.io

You can write and test your regular expression using regex101.com. Be sure to select the Go flavor before you begin.

另请参阅

38 - first

将以下英文翻译为中文:

first

https://gohugo.io/functions/first/

Slices an array to only the first N elements.

语法

first LIMIT COLLECTION

first works in a similar manner to the limit keyword in SQL. It reduces the array to only the first N elements. It takes the array and number of elements as input.

first takes two arguments:

  1. number of elements
  2. array or slice of maps or structs

layout/_default/section.html

1
2
3
{{ range first 10 .Pages }}
    {{ .Render "summary" }}
{{ end }}

Note: Exclusive to first, LIMIT can be ‘0’ to return an empty array.

first and where Together

Using first and where together can be very powerful. Below snippet gets a list of posts only from main sections, sorts it by the title parameter, and then ranges through only the first 5 posts in that list:

first-and-where-together.html

1
2
3
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }}
   {{ .Content }}
{{ end }}

另请参阅

39 - float

将以下英文翻译为中文:

float

https://gohugo.io/functions/float/

Casts a value to a decimal (base 10) floating point value.

语法

float INPUT

With a decimal (base 10) input:

1
2
3
4
5
6
7
8
{{ float 11 }} → 11 (float64)
{{ float "11" }} → 11 (float64)

{{ float 11.1 }} → 11.1 (float64)
{{ float "11.1" }} → 11.1 (float64)

{{ float 11.9 }} → 11.9 (float64)
{{ float "11.9" }} → 11.9 (float64)

With a binary (base 2) input:

1
{{ float 0b11 }} → 3 (float64)

With an octal (base 8) input (use either notation):

1
2
3
4
{{ float 011 }} → 9 (float64)
{{ float "011" }} → 11 (float64)

{{ float 0o11 }} → 9 (float64)

With a hexadecimal (base 16) input:

1
{{ float 0x11 }} → 17 (float64)

另请参阅

40 - ge

将以下英文翻译为中文:

ge

https://gohugo.io/functions/ge/

Returns the boolean truth of arg1 >= arg2.

语法

ge ARG1 ARG2
{{ if ge 10 5 }}true{{ end }}

另请参阅

41 - getenv

将以下英文翻译为中文:

getenv

https://gohugo.io/functions/getenv/

Returns the value of an environment variable, or an empty string if the environment variable is not set.

语法

os.Getenv VARIABLE
getenv VARIABLE

Examples:

1
2
{{ os.Getenv "HOME" }} --> /home/victor
{{ os.Getenv "USER" }} --> victor

You can pass values when building your site:

1
2
3
4
5
6
7
MY_VAR1=foo MY_VAR2=bar hugo

OR

export MY_VAR1=foo
export MY_VAR2=bar
hugo

And then retrieve the values within a template:

1
2
{{ os.Getenv "MY_VAR1" }} --> foo
{{ os.Getenv "MY_VAR2" }} --> bar

With Hugo v0.91.0 and later, you must explicitly allow access to environment variables. For details, review Hugo’s Security Policy. By default, environment variables beginning with HUGO_ are allowed when using the os.Getenv function.

42 - group

将以下英文翻译为中文:

group

https://gohugo.io/functions/group/

group groups a list of pages.

语法

PAGES | group KEY

layouts/partials/groups.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{{ $new := .Site.RegularPages | first 10 | group "New" }}
{{ $old := .Site.RegularPages | last 10 | group "Old" }}
{{ $groups := slice $new $old }}
{{ range $groups }}
<h3>{{ .Key }}{{/* Prints "New", "Old" */}}</h3>
<ul>
    {{ range .Pages }}
    <li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
    <div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
    </li>
    {{ end }}
</ul>
{{ end }}

The page group you get from group is of the same type you get from the built-in group methods in Hugo. The above example can even be paginated.

另请参阅

43 - gt

将以下英文翻译为中文:

gt

https://gohugo.io/functions/gt/

Returns the boolean truth of arg1 > arg2.

语法

gt ARG1 ARG2
{{ if gt 10 5 }}true{{ end }}

另请参阅

44 - highlight

将以下英文翻译为中文:

highlight

https://gohugo.io/functions/highlight/

Renders code with a syntax highlighter.

语法

transform.Highlight INPUT LANG [OPTIONS]
highlight INPUT LANG [OPTIONS]

The highlight function uses the Chroma syntax highlighter, supporting over 200 languages with more than 40 available styles.

Parameters

  • INPUT

    The code to highlight.

  • LANG

    The language of the code to highlight. Choose from one of the supported languages. Case-insensitive.

  • OPTIONS

    An optional, comma-separated list of zero or more options. Set default values in site configuration.

Options

  • lineNos

    Boolean. Default is false. Display a number at the beginning of each line.

  • lineNumbersInTable

    Boolean. Default is true. Render the highlighted code in an HTML table with two cells. The left table cell contains the line numbers. The right table cell contains the code, allowing a user to select and copy the code without line numbers. Irrelevant if lineNos is false.

  • anchorLineNos

    Boolean. Default is false. Render each line number as an HTML anchor element, and set the id attribute of the surrounding <span> to the line number. Irrelevant if lineNos is false.

  • lineAnchors

    String. Default is "". When rendering a line number as an HTML anchor element, prepend this value to the id attribute of the surrounding <span>. This provides unique id attributes when a page contains two or more code blocks. Irrelevant if lineNos or anchorLineNos is false.

  • lineNoStart

    Integer. Default is 1. The number to display at the beginning of the first line. Irrelevant if lineNos is false.

  • hl_Lines

    String. Default is "". A space-separated list of lines to emphasize within the highlighted code. To emphasize lines 2, 3, 4, and 7, set this value to 2-4 7. This option is independent of the lineNoStart option.

  • hl_inline

    Boolean. Default is false. Render the highlighted code without a wrapping container.

  • style

    String. Default is monokai. The CSS styles to apply to the highlighted code. See the style gallery for examples. Case-sensitive.

  • noClasses

    Boolean. Default is true. Use inline CSS styles instead of an external CSS file. To use an external CSS file, set this value to false and generate the file with the hugo client.

  • tabWidth

    Integer. Default is 4. Substitute this number of spaces for each tab character in your highlighted code. Irrelevant if noClasses is false.

  • guessSyntax

    Boolean. Default is false. If the LANG parameter is blank or an unrecognized language, auto-detect the language if possible, otherwise use a fallback language.

Instead of specifying both lineNos and lineNumbersInTable, you can use the following shorthand notation:

  • lineNos=inline

    equivalent to lineNos=true and lineNumbersInTable=false

  • lineNos=table

    equivalent to lineNos=true and lineNumbersInTable=true

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{ $input := `fmt.Println("Hello World!")` }}
{{ transform.Highlight $input "go" }}

{{ $input := `console.log('Hello World!');` }}
{{ $lang := "js" }}
{{ transform.Highlight $input $lang "lineNos=table, style=api" }}

{{ $input := `echo "Hello World!"` }}
{{ $lang := "bash" }}
{{ $options := slice "lineNos=table" "style=dracula" }}
{{ transform.Highlight $input $lang (delimit $options ",") }}

另请参阅

45 - hmac

将以下英文翻译为中文:

hmac

https://gohugo.io/functions/hmac/

Returns a cryptographic hash that uses a key to sign a message.

语法

crypto.HMAC HASH_TYPE KEY MESSAGE [ENCODING]
hmac HASH_TYPE KEY MESSAGE [ENCODING]

Set the HASH_TYPE argument to md5, sha1, sha256, or sha512.

Set the optional ENCODING argument to either hex (default) or binary.

1
2
3
4
5
6
7
8
{{ hmac "sha256" "Secret key" "Secret message" }}
5cceb491f45f8b154e20f3b0a30ed3a6ff3027d373f85c78ffe8983180b03c84

{{ hmac "sha256" "Secret key" "Secret message" "hex" }}
5cceb491f45f8b154e20f3b0a30ed3a6ff3027d373f85c78ffe8983180b03c84

{{ hmac "sha256" "Secret key" "Secret message" "binary" | base64Encode }}
XM60kfRfixVOIPOwow7Tpv8wJ9Nz+Fx4/+iYMYCwPIQ=

另请参阅

46 - htmlEscape

将以下英文翻译为中文:

htmlEscape

https://gohugo.io/functions/htmlescape/

Returns the given string with the reserved HTML codes escaped.

语法

htmlEscape INPUT

In the result & becomes & and so on. It escapes only: <, >, &, ' and ".

1
{{ htmlEscape "Hugo & Caddy > WordPress & Apache" }} → "Hugo &amp; Caddy &gt; WordPress &amp; Apache"

另请参阅

47 - htmlUnescape

将以下英文翻译为中文:

htmlUnescape

https://gohugo.io/functions/htmlunescape/

Returns the given string with HTML escape codes un-escaped.

语法

htmlUnescape INPUT

htmlUnescape returns the given string with HTML escape codes un-escaped.

Remember to pass the output of this to safeHTML if fully un-escaped characters are desired. Otherwise, the output will be escaped again as normal.

1
{{ htmlUnescape "Hugo &amp; Caddy &gt; WordPress &amp; Apache" }} → "Hugo & Caddy > WordPress & Apache"

48 - hugo

将以下英文翻译为中文:

hugo

https://gohugo.io/functions/hugo/

The hugo function provides easy access to Hugo-related data.

语法

hugo

hugo returns an instance that contains the following functions:

  • hugo.Generator

    <meta> tag for the version of Hugo that generated the site. hugo.Generator outputs a complete HTML tag; e.g. <meta name="generator" content="Hugo 0.63.2">

  • hugo.Version

    the current version of the Hugo binary you are using e.g. 0.99.1

  • hugo.GoVersion

    returns the version of Go that the Hugo binary was built with. New in v0.101.0

  • hugo.Environment

    the current running environment as defined through the --environment cli tag

  • hugo.CommitHash

    the git commit hash of the current Hugo binary e.g. 0e8bed9ccffba0df554728b46c5bbf6d78ae5247

  • hugo.BuildDate

    the compile date of the current Hugo binary formatted with RFC 3339 e.g. 2002-10-02T10:00:00-05:00

  • hugo.IsExtended

    whether this is the extended Hugo binary.

  • hugo.IsProduction

    returns true if hugo.Environment is set to the production environment

  • hugo.Deps

    See hugo.Deps

hugo.Deps

New in v0.92.0

hugo.Deps returns a list of dependencies for a project (either Hugo Modules or local theme components).

Each dependency contains:

  • Path (string)

    Returns the path to this module. This will either be the module path, e.g. “github.com/gohugoio/myshortcodes”, or the path below your /theme folder, e.g. “mytheme”.

  • Version (string)

    The module version.

  • Vendor (bool)

    Whether this dependency is vendored.

  • Time (time.Time)

    Time version was created.

  • Owner

    In the dependency tree, this is the first module that defines this module as a dependency.

  • Replace (*Dependency)

    Replaced by this dependency.

An example table listing the dependencies:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 <h2>Dependencies</h2>
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Owner</th>
      <th scope="col">Path</th>
      <th scope="col">Version</th>
      <th scope="col">Time</th>
      <th scope="col">Vendor</th>
    </tr>
  </thead>
  <tbody>
    {{ range $index, $element := hugo.Deps }}
    <tr>
      <th scope="row">{{ add $index 1 }}</th>
      <td>{{ with $element.Owner }}{{ .Path }}{{ end }}</td>
      <td>
        {{ $element.Path }}
        {{ with $element.Replace }}
        => {{ .Path }}
        {{ end }}
      </td>
      <td>{{ $element.Version }}</td>
      <td>{{ with $element.Time }}{{ . }}{{ end }}</td>
      <td>{{ $element.Vendor }}</td>
    </tr>
    {{ end }}
  </tbody>
</table>

49 - humanize

将以下英文翻译为中文:

humanize

https://gohugo.io/functions/humanize/

Returns the humanized version of an argument with the first letter capitalized.

语法

humanize INPUT

If the input is either an int64 value or the string representation of an integer, humanize returns the number with the proper ordinal appended.

1
2
3
4
{{ humanize "my-first-post" }} → "My first post"
{{ humanize "myCamelPost" }} → "My camel post"
{{ humanize "52" }} → "52nd"
{{ humanize 103 }} → "103rd"

另请参阅

50 - i18n

将以下英文翻译为中文:

i18n

https://gohugo.io/functions/i18n/

Translates a piece of content based on your i18n configuration files.

语法

i18n KEY
T KEY
lang.Translate KEY

This translates a piece of content based on your i18n/en-US.toml files. You can use the go-i18n tools to manage your translations. The translations can exist in both the theme and at the root of your repository.

1
{{ i18n "translation_id" }}

T is an alias to i18n. E.g. {{ T "translation_id" }}.

Query a flexible translation with variables

Often you will want to use the page variables in the translation strings. To do so, pass the . context when calling i18n:

1
{{ i18n "wordCount" . }}

The function will pass the . context to the "wordCount" id:

i18n/en-US.

=== “yaml”

``` yaml
wordCount:
  other: This article has {{ .WordCount }} words.
```

=== “toml”

``` toml
[wordCount]
  other = 'This article has {{ .WordCount }} words.'
```

=== “json”

``` json
{
   "wordCount": {
      "other": "This article has {{ .WordCount }} words."
   }
}
```

Assume .WordCount in the context has value is 101. The result will be:

This article has 101 words.

For more information about string translations, see Translation of Strings in Multilingual Mode.

另请参阅

51 - index

将以下英文翻译为中文:

index

https://gohugo.io/functions/index-function/

Looks up the index(es) or key(s) of the data structure passed into it.

语法

index COLLECTION INDEXES
index COLLECTION KEYS

The index functions returns the result of indexing its first argument by the following arguments. Each indexed item must be a map or a slice, e.g.:

1
2
3
4
{{ $slice := slice "a" "b" "c" }}
{{ index $slice 1 }} => b
{{ $map := dict "a" 100 "b" 200 }}
{{ index $map "b" }} => 200

The function takes multiple indices as arguments, and this can be used to get nested values, e.g.:

1
2
3
4
{{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $map "c" 1 }} => 20
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $map "c" "e" }} => 20

You may write multiple indices as a slice:

1
2
3
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $slice := slice "c" "e" }}
{{ index $map $slice }} => 20

Example: Load Data from a Path Based on Front Matter Params

Assume you want to add a location = "" field to your front matter for every article written in content/vacations/. You want to use this field to populate information about the location at the bottom of the article in your single.html template. You also have a directory in data/locations/ that looks like the following:

.
└── data
    └── locations
        ├── abilene.toml
        ├── chicago.toml
        ├── oslo.toml
        └── provo.toml

Here is an example:

data/locations/oslo.

=== “yaml”

``` yaml
pop_city: 658390
pop_metro: 1717900
website: https://www.oslo.kommune.no
```

=== “toml”

``` toml
pop_city = 658390
pop_metro = 1717900
website = 'https://www.oslo.kommune.no'
```

=== “json”

``` json
{
   "pop_city": 658390,
   "pop_metro": 1717900,
   "website": "https://www.oslo.kommune.no"
}
```

The example we will use will be an article on Oslo, whose front matter should be set to exactly the same name as the corresponding file name in data/locations/:

content/articles/oslo.md

=== “yaml”

``` yaml
---
location: oslo
title: My Norwegian Vacation
---
```

=== “toml”

``` toml
+++
location = 'oslo'
title = 'My Norwegian Vacation'
+++
```

=== “json”

``` json
{
   "location": "oslo",
   "title": "My Norwegian Vacation"
}
```

The content of oslo.toml can be accessed from your template using the following node path: .Site.Data.locations.oslo. However, the specific file you need is going to change according to the front matter.

This is where the index function is needed. index takes 2 parameters in this use case:

  1. The node path
  2. A string corresponding to the desired data; e.g.—
1
{{ index .Site.Data.locations "oslo" }}

The variable for .Params.location is a string and can therefore replace oslo in the example above:

1
2
{{ index .Site.Data.locations .Params.location }}
=> map[website:https://www.oslo.kommune.no pop_city:658390 pop_metro:1717900]

Now the call will return the specific file according to the location specified in the content’s front matter, but you will likely want to write specific properties to the template. You can do this by continuing down the node path via dot notation (.):

1
2
{{ (index .Site.Data.locations .Params.location).pop_city }}
=> 658390

52 - Image Filters

将以下英文翻译为中文:

Image Filters

https://gohugo.io/functions/images/

The images namespace provides a list of filters and other image related functions.

See images.Filter for how to apply these filters to an image.

Overlay

Overlay creates a filter that overlays the source image at position x y, e.g:

1
2
{{ $logoFilter := (images.Overlay $logo 50 50 ) }}
{{ $img := $img | images.Filter $logoFilter }}

A shorter version of the above, if you only need to apply the filter once:

1
{{ $img := $img.Filter (images.Overlay $logo 50 50 )}}

The above will overlay $logo in the upper left corner of $img (at position x=50, y=50).

Text

Using the Text filter, you can add text to an image.

The following example will add the text Hugo rocks! to the image with the specified color, size and position.

1
2
3
4
5
6
7
8
{{ $img := resources.Get "/images/background.png" }}
{{ $img = $img.Filter (images.Text "Hugo rocks!" (dict
    "color" "#ffffff"
    "size" 60
    "linespacing" 2
    "x" 10
    "y" 20
))}}

You can load a custom font if needed. Load the font as a Hugo Resource and set it as an option:

1
2
3
4
5
{{ $font := resources.GetRemote "https://github.com/google/fonts/raw/main/apache/roboto/static/Roboto-Black.ttf" }}
{{ $img := resources.Get "/images/background.png" }}
{{ $img = $img.Filter (images.Text "Hugo rocks!" (dict
    "font" $font
))}}

Brightness

Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100).

ColorBalance

ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500).

Colorize

Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100).

Contrast

Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100).

Gamma

Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it.

GaussianBlur

GaussianBlur creates a filter that applies a gaussian blur to an image.

Grayscale

Grayscale creates a filter that produces a grayscale version of an image.

Hue

Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180.

Invert

Invert creates a filter that negates the colors of an image.

Pixelate

Pixelate creates a filter that applies a pixelation effect to an image.

Saturation

Saturation creates a filter that changes the saturation of an image.

Sepia

Sepia creates a filter that produces a sepia-toned version of an image.

Sigmoid

Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It’s a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.

UnsharpMask

UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.

Other Functions

Filter

Can be used to apply a set of filters to an image:

1
{{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}

Also see the Filter Method.

ImageConfig

Parses the image and returns the height, width, and color model.

The imageConfig function takes a single parameter, a file path (string) relative to the project’s root directory, with or without a leading slash.

1
2
3
{{ with (imageConfig "favicon.ico") }}
favicon.ico: {{ .Width }} x {{ .Height }}
{{ end }}

另请参阅

53 - in

将以下英文翻译为中文:

in

https://gohugo.io/functions/in/

Checks if an element is in an array or slice–or a substring in a string—and returns a boolean.

语法

in SET ITEM

The elements supported are strings, integers and floats, although only float64 will match as expected.

In addition, in can also check if a substring exists in a string.

1
2
{{ if in .Params.tags "Git" }}Follow me on GitHub!{{ end }}
{{ if in "this string contains a substring" "substring" }}Substring found!{{ end }}

另请参阅

54 - int

将以下英文翻译为中文:

int

https://gohugo.io/functions/int/

Casts a value to a decimal (base 10) integer.

语法

int INPUT

With a decimal (base 10) input:

1
2
3
4
5
{{ int 11 }} → 11 (int)
{{ int "11" }} → 11 (int)

{{ int 11.1 }} → 11 (int)
{{ int 11.9 }} → 11 (int)

With a binary (base 2) input:

1
2
{{ int 0b11 }} → 3 (int)
{{ int "0b11" }} → 3 (int)

With an octal (base 8) input (use either notation):

1
2
3
4
5
{{ int 011 }} → 9 (int)
{{ int "011" }} → 9 (int)

{{ int 0o11 }} → 9 (int)
{{ int "0o11" }} → 9 (int)

With a hexadecimal (base 16) input:

1
2
{{ int 0x11 }} → 17 (int)
{{ int "0x11" }} → 17 (int)

Values with a leading zero are octal (base 8). When casting a string representation of a decimal (base 10) number, remove leading zeros:

{{ strings.TrimLeft "0" "0011" | int }} → 11

另请参阅

55 - intersect

将以下英文翻译为中文:

intersect

https://gohugo.io/functions/intersect/

Returns the common elements of two arrays or slices, in the same order as the first array.

语法

intersect SET1 SET2

A useful example is to use it as AND filters when combined with where:

AND filter in where query

1
2
3
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages := $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}

The above fetches regular pages not of page or about type unless they are pinned. And finally, we exclude all pages with no images set in Page params.

See union for OR.

另请参阅

56 - isset

将以下英文翻译为中文:

isset

https://gohugo.io/functions/isset/

Returns true if the parameter is set.

语法

isset COLLECTION INDEX
isset COLLECTION KEY

Takes either a slice, array, or channel and an index or a map and a key as input.

1
{{ if isset .Params "project_url" }} {{ index .Params "project_url" }}{{ end }}

All site-level configuration keys are stored as lower case. Therefore, a myParam key-value set in your site configuration file needs to be accessed with {{ if isset .Site.Params "myparam" }} and not with {{ if isset .Site.Params "myParam" }}. Note that you can still access the same config key with .Site.Params.myParam or .Site.Params.myparam, for example, when using with. This restriction also applies when accessing page-level front matter keys from within shortcodes.

57 - jsonify

将以下英文翻译为中文:

jsonify

https://gohugo.io/functions/jsonify/

Encodes a given object to JSON.

语法

jsonify INPUT
jsonify OPTIONS INPUT

Jsonify encodes a given object to JSON.

To customize the printing of the JSON, pass a dictionary of options as the first argument. Supported options are “prefix” and “indent”. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

1
2
3
{{ dict "title" .Title "content" .Plain | jsonify }}
{{ dict "title" .Title "content" .Plain | jsonify (dict "indent" "  ") }}
{{ dict "title" .Title "content" .Plain | jsonify (dict "prefix" " " "indent" "  ") }}

Jsonify options

  • indent ("")

    Indentation to use.

  • prefix ("")

    Indentation prefix.

  • noHTMLEscape (false)

    Disable escaping of problematic HTML characters inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

See also the .PlainWords, .Plain, and .RawContent page variables.

另请参阅

58 - lang

将以下英文翻译为中文:

lang.FormatAccounting

https://gohugo.io/functions/lang/

FormatAccounting returns the currency representation of number for the given currency and precision for the current language in accounting notation.

The return value is formatted with at least two decimal places.

语法

lang.FormatAccounting PRECISION, CURRENCY, NUMBER

Examples

1
{{ 512.5032 | lang.FormatAccounting 2 "NOK" }} ---> NOK512.50

lang.FormatCurrency

FormatCurrency returns the currency representation of number for the given currency and precision for the current language.

The return value is formatted with at least two decimal places.

语法

lang.FormatCurrency PRECISION, CURRENCY, NUMBER

Examples

1
{{ 512.5032 | lang.FormatCurrency 2 "USD" }} ---> $512.50

lang.FormatNumber

FormatNumber formats number with the given precision for the current language.

语法

lang.FormatNumber PRECISION, NUMBER

Examples

1
{{ 512.5032 | lang.FormatNumber 2 }} ---> 512.50

lang.FormatNumberCustom

FormatNumberCustom formats a number with the given precision using the negative, decimal, and grouping options. The options parameter is a string consisting of <negative> <decimal> <grouping>. The default options value is - . ,.

Note that numbers are rounded up at 5 or greater. So, with precision set to 0, 1.5 becomes 2, and 1.4 becomes 1.

For a simpler function that adapts to the current language, see FormatNumber.

语法

lang.FormatNumberCustom PRECISION, NUMBER, OPTIONS

Examples

1
2
3
4
5
{{ lang.FormatNumberCustom 2 12345.6789 }} ---> 12,345.68
{{ lang.FormatNumberCustom 2 12345.6789 "- , ." }} ---> 12.345,68
{{ lang.FormatNumberCustom 6 -12345.6789 "- ." }} ---> -12345.678900
{{ lang.FormatNumberCustom 0 -12345.6789 "- . ," }} ---> -12,346
{{ -98765.4321 | lang.FormatNumberCustom 2 }} ---> -98,765.43

lang.FormatPercent

FormatPercent formats number with the given precision for the current language. Note that the number is assumed to be a percentage.

语法

lang.FormatPercent PRECISION, NUMBER

Examples

1
{{ 512.5032 | lang.FormatPercent 2 }} ---> 512.50%

lang.Translate

Translate returns a translated string for id.

语法

lang.Translate ID, ARGS

Aliases

i18n, T

59 - lang.Merge

将以下英文翻译为中文:

lang.Merge

https://gohugo.io/functions/lang.merge/

Merge missing translations from other languages.

语法

lang.Merge FROM TO

As an example:

1
{{ $pages := .Site.RegularPages | lang.Merge $frSite.RegularPages | lang.Merge $enSite.RegularPages }}

Will “fill in the gaps” in the current site with, from left to right, content from the French site, and lastly the English.

A more practical example is to fill in the missing translations from the other languages:

1
2
3
4
{{ $pages := .Site.RegularPages }}
{{ range .Site.Home.Translations }}
{{ $pages = $pages | lang.Merge .Site.RegularPages }}
{{ end }}

另请参阅

60 - last

将以下英文翻译为中文:

last

https://gohugo.io/functions/last/

slices an array to only the last Nth elements.

语法

last INDEX COLLECTION
{{ range last 10 .Pages }}
  {{ .Render "summary" }}
{{ end }}

61 - le

将以下英文翻译为中文:

le

https://gohugo.io/functions/le/

Returns the boolean truth of arg1 <= arg2.

语法

le ARG1 ARG2
{{ if le 5 10 }}true{{ end }}

另请参阅

62 - len

将以下英文翻译为中文:

len

https://gohugo.io/functions/len/

Returns the length of a string, slice, map, or collection.

语法

len INPUT

With a string:

1
2
{{ "ab" | len }} → 2
{{ "" | len }} → 0

With a slice:

1
2
{{ slice "a" "b" | len }} → 2
{{ slice | len }} → 0

With a map:

1
2
{{ dict "a" 1 "b" 2  | len }} → 2
{{ dict | len }} → 0

With a collection:

1
{{ site.RegularPages | len }} → 42

You may also determine the number of pages in a collection with:

1
{{ site.RegularPages.Len }} → 42

另请参阅

63 - lower

将以下英文翻译为中文:

lower

https://gohugo.io/functions/lower/

Converts all characters in the provided string to lowercase.

语法

lower INPUT
strings.ToLower INPUT

Note that lower can be applied in your templates in more than one way:

1
2
{{ lower "BatMan" }} → "batman"
{{ "BatMan" | lower }} → "batman"

另请参阅

64 - lt

将以下英文翻译为中文:

lt

https://gohugo.io/functions/lt/

Returns the boolean truth of arg1 < arg2.

语法

lt ARG1 ARG2
{{ if lt 5 10 }}true{{ end }}

另请参阅

65 - markdownify

将以下英文翻译为中文:

markdownify

https://gohugo.io/functions/markdownify/

Renders markdown to HTML.

语法

markdownify INPUT
{{ .Title | markdownify }}

If the resulting HTML is a single paragraph, Hugo removes the wrapping p tags to produce inline HTML as required per the example above.

To keep the wrapping p tags for a single paragraph, use the .Page.RenderString method, setting the display option to block.

If the resulting HTML is two or more paragraphs, Hugo leaves the wrapping p tags in place.

Although the markdownify function honors markdown render hooks when rendering markdown to HTML, use the .Page.RenderString method instead of markdownify if a render hook accesses .Page context. See issue #9692 for details.

另请参阅

66 - Math

将以下英文翻译为中文:

Math

https://gohugo.io/functions/math/

Hugo provides mathematical operators in templates.

FunctionDescriptionExample
addAdds two or more numbers.{{ add 12 3 2 }}17
If one of the numbers is a float, the result is a float.{{ add 1.1 2 }}3.1
subSubtracts one or more numbers from the first number.{{ sub 12 3 2 }}7
If one of the numbers is a float, the result is a float.{{ sub 3 2.5 }}0.5
mulMultiplies two or more numbers.{{ mul 12 3 2 }}72
If one of the numbers is a float, the result is a float.{{ mul 2 3.1 }}6.2
divDivides the first number by one or more numbers.{{ div 12 3 2 }}2
If one of the numbers is a float, the result is a float.{{ div 6 4.0 }}1.5
modModulus of two integers.{{ mod 15 3 }}0
modBoolBoolean of modulus of two integers. Evaluates to true if result equals 0.{{ modBool 15 3 }}true
math.CeilReturns the least integer value greater than or equal to the given number.{{ math.Ceil 2.1 }}3
math.FloorReturns the greatest integer value less than or equal to the given number.{{ math.Floor 1.9 }}1
math.LogReturns the natural logarithm of the given number.{{ math.Log 42 }}3.737
math.MaxReturns the greater of two or more numbers.{{ math.Max 12 3 2 }}12
math.MinReturns the smaller of two or more numbers.{{ math.Min 12 3 2 }}2
math.PowReturns the first number raised to the power of the second number.{{ math.Pow 2 3 }}8
math.RoundReturns the nearest integer, rounding half away from zero.{{ math.Round 1.5 }}2
math.SqrtReturns the square root of the given number.{{ math.Sqrt 81 }}9

另请参阅

67 - md5

将以下英文翻译为中文:

md5

https://gohugo.io/functions/md5/

hashes the given input and returns its MD5 checksum.

语法

md5 INPUT
{{ md5 "Hello world, gophers!" }}
<!-- returns the string "b3029f756f98f79e7f1b7f1d1f0dd53b" -->

This can be useful if you want to use Gravatar for generating a unique avatar:

1
<img src="https://www.gravatar.com/avatar/{{ md5 "your@email.com" }}?s=100&d=identicon">

68 - merge

将以下英文翻译为中文:

merge

https://gohugo.io/functions/merge/

Returns the result of merging two or more maps.

语法

collections.Merge MAP MAP...
merge MAP MAP...

Returns the result of merging two or more maps from left to right. If a key already exists, merge updates its value. If a key is absent, merge inserts the value under the new key.

Key handling is case-insensitive.

The following examples use these map definitions:

1
2
3
{{ $m1 := dict "x" "foo" }}
{{ $m2 := dict "x" "bar" "y" "wibble" }}
{{ $m3 := dict "x" "baz" "y" "wobble" "z" (dict "a" "huey") }}

Example 1

1
2
3
4
5
{{ $merged := merge $m1 $m2 $m3 }}

{{ $merged.x }}   --> baz
{{ $merged.y }}   --> wobble
{{ $merged.z.a }} --> huey

Example 2

1
2
3
4
5
{{ $merged := merge $m3 $m2 $m1 }}

{{ $merged.x }}   --> foo
{{ $merged.y }}   --> wibble
{{ $merged.z.a }} --> huey

Example 3

1
2
3
4
5
{{ $merged := merge $m2 $m3 $m1 }}

{{ $merged.x }}   --> foo
{{ $merged.y }}   --> wobble
{{ $merged.z.a }} --> huey

Example 4

1
2
3
4
5
{{ $merged := merge $m1 $m3 $m2 }}

{{ $merged.x }}   --> bar
{{ $merged.y }}   --> wibble
{{ $merged.z.a }} --> huey

Regardless of depth, merging only applies to maps. For slices, use append.

另请参阅

69 - ne

将以下英文翻译为中文:

ne

https://gohugo.io/functions/ne/

Returns the boolean truth of arg1 != arg2.

语法

ne ARG1 ARG2
{{ if ne .Section "blog" }}current{{ end }}

另请参阅

70 - now

将以下英文翻译为中文:

now

https://gohugo.io/functions/now/

Returns the current local time

语法

now

See time.Time.

For example, building your site on June 24, 2017, with the following templating:

1
2
3
<div>
    <small>&copy; {{ now.Format "2006" }}</small>
</div>

would produce the following:

1
2
3
<div>
    <small>&copy; 2017</small>
</div>

The above example uses the .Format function, which page includes a full listing of date formatting using Go’s layout string.

Older Hugo themes may still be using the obsolete Page’s .Now (uppercase with leading dot), which causes build error that looks like the following:

ERROR ... Error while rendering "..." in "...": ...
executing "..." at <.Now.Format>:
can't evaluate field Now in type *hugolib.PageOutput

Be sure to use now (lowercase with no leading dot) in your templating.

另请参阅

71 - os.Stat

将以下英文翻译为中文:

os.Stat

https://gohugo.io/functions/os.stat/

Returns a FileInfo structure describing a file or directory.

语法

os.Stat PATH

The os.Stat function attempts to resolve the path relative to the root of your project directory. If a matching file or directory is not found, it will attempt to resolve the path relative to the contentDir. A leading path separator (/) is optional.

1
2
3
4
5
6
7
8
{{ $f := os.Stat "README.md" }}
{{ $f.IsDir }}    --> false (bool)
{{ $f.ModTime }}  --> 2021-11-25 10:06:49.315429236 -0800 PST (time.Time)
{{ $f.Name }}     --> README.md (string)
{{ $f.Size }}     --> 241 (int64)

{{ $d := os.Stat "content" }}
{{ $d.IsDir }}    --> true (bool)

Details of the FileInfo structure are available in the Go documentation.

另请参阅

72 - partialCached

将以下英文翻译为中文:

partialCached

https://gohugo.io/functions/partialcached/

Allows for caching of partials that do not need to be re-rendered on every invocation.

语法

partialCached LAYOUT INPUT [VARIANT...]

The partialCached template function can offer significant performance gains for complex templates that don’t need to be re-rendered on every invocation.

Note: Each Site (or language) has its own partialCached cache, so each site will execute a partial once.

Note: Hugo renders pages in parallel, and will render the partial more than once with concurrent calls to the partialCached function. After Hugo caches the rendered partial, new pages entering the build pipeline will use the cached result.

Here is the simplest usage:

1
{{ partialCached "footer.html" . }}

You can also pass additional parameters to partialCached to create variants of the cached partial. For example, if you have a complex partial that should be identical when rendered for pages within the same section, you could use a variant based upon section so that the partial is only rendered once per section:

partial-cached-example.html

1
{{ partialCached "footer.html" . .Section }}

If you need to pass additional parameters to create unique variants, you can pass as many variant parameters as you need:

1
{{ partialCached "footer.html" . .Params.country .Params.province }}

Note that the variant parameters are not made available to the underlying partial template. They are only use to create a unique cache key. Since Hugo 0.61.0 you can use any object as cache key(s), not just strings.

See also The Full Partial Series Part 1: Caching!.

另请参阅

73 - path.Base

将以下英文翻译为中文:

path.Base

https://gohugo.io/functions/path.base/

Base returns the last element of a path.

语法

path.Base PATH

path.Base returns the last element of PATH.

If PATH is empty, . is returned.

Note: On Windows, PATH is converted to slash (/) separators.

1
2
3
4
{{ path.Base "a/news.html" }} → "news.html"
{{ path.Base "news.html" }} → "news.html"
{{ path.Base "a/b/c" }} → "c"
{{ path.Base "/x/y/z/" }} → "z"

另请参阅

74 - path.BaseName

将以下英文翻译为中文:

path.BaseName

https://gohugo.io/functions/path.basename/

BaseName returns the last element of a path, removing the extension if present.

语法

path.BaseName PATH

If PATH is empty, . is returned.

Note: On Windows, PATH is converted to slash (/) separators.

1
2
3
4
{{ path.BaseName "a/news.html" }} → "news"
{{ path.BaseName "news.html" }} → "news"
{{ path.BaseName "a/b/c" }} → "c"
{{ path.BaseName "/x/y/z/" }} → "z"

另请参阅

75 - path.Clean

将以下英文翻译为中文:

path.Clean

https://gohugo.io/functions/path.clean/

Replaces path separators with slashes (/) and removes extraneous separators.

语法

path.Clean PATH

path.Clean replaces path separators with slashes (/) and removes extraneous separators, including trailing separators.

1
2
{{ path.Clean "foo//bar" }} → "foo/bar"
{{ path.Clean "/foo/bar/" }} → "/foo/bar"

On a Windows system, if .File.Path is foo\bar.md, then:

1
{{ path.Clean .File.Path }} → "foo/bar.md"

另请参阅

76 - path.Dir

将以下英文翻译为中文:

path.Dir

https://gohugo.io/functions/path.dir/

Dir returns all but the last element of a path.

语法

path.Dir PATH

path.Dir returns all but the last element of PATH, typically PATH’s directory.

The returned path will never end in a slash. If PATH is empty, . is returned.

Note: On Windows, PATH is converted to slash (/) separators.

1
2
3
4
{{ path.Dir "a/news.html" }} → "a"
{{ path.Dir "news.html" }} → "."
{{ path.Dir "a/b/c" }} → "a/b"
{{ path.Dir "/x/y/z" }} → "/x/y"

另请参阅

77 - path.Ext

将以下英文翻译为中文:

path.Ext

https://gohugo.io/functions/path.ext/

Ext returns the file name extension of a path.

语法

path.Ext PATH

path.Ext returns the file name extension PATH.

The extension is the suffix beginning at the final dot in the final slash-separated element PATH; it is empty if there is no dot.

Note: On Windows, PATH is converted to slash (/) separators.

1
{{ path.Ext "a/b/c/news.html" }} → ".html"

另请参阅

78 - path.Join

将以下英文翻译为中文:

path.Join

https://gohugo.io/functions/path.join/

Join path elements into a single path.

语法

path.Join ELEMENT...

path.Join joins path elements into a single path, adding a separating slash if necessary. All empty strings are ignored.

Note: All path elements on Windows are converted to slash (’/’) separators.

1
2
3
{{ path.Join "partial" "news.html" }} → "partial/news.html"
{{ path.Join "partial/" "news.html" }} → "partial/news.html"
{{ path.Join "foo/baz" "bar" }} → "foo/baz/bar"

另请参阅

79 - path.Split

将以下英文翻译为中文:

path.Split

https://gohugo.io/functions/path.split/

Split path immediately following the final slash.

语法

path.Split PATH

path.Split splits PATH immediately following the final slash, separating it into a directory and a base component.

The returned values have the property that PATH = DIR+BASE. If there is no slash in PATH, it returns an empty directory and the base is set to PATH.

Note: On Windows, PATH is converted to slash (/) separators.

1
2
3
{{ $dirFile := path.Split "a/news.html" }} → $dirFile.Dir → "a/", $dirFile.File → "news.html"
{{ $dirFile := path.Split "news.html" }} → $dirFile.Dir → "", $dirFile.File → "news.html"
{{ $dirFile := path.Split "a/b/c" }} → $dirFile.Dir → "a/b/", $dirFile.File →  "c"

另请参阅

80 - plainify

将以下英文翻译为中文:

plainify

https://gohugo.io/functions/plainify/

Strips any HTML and returns the plain text version of the provided string.

语法

plainify INPUT
{{ "<b>BatMan</b>" | plainify }} → "BatMan"

See also the .PlainWords, .Plain, and .RawContent page variables.

另请参阅

81 - pluralize

将以下英文翻译为中文:

pluralize

https://gohugo.io/functions/pluralize/

Pluralizes the given word according to a set of common English pluralization rules

语法

pluralize INPUT
{{ "cat" | pluralize }} → "cats"

另请参阅

82 - print

将以下英文翻译为中文:

print

https://gohugo.io/functions/print/

Prints the default representation of the given arguments using the standard fmt.Print function.

语法

print INPUT

See the go doc for additional information.

1
2
3
{{ print "foo" }} → "foo"
{{ print "foo" "bar" }} → "foobar"
{{ print (slice 1 2 3) }} → [1 2 3]

另请参阅

83 - printf

将以下英文翻译为中文:

printf

https://gohugo.io/functions/printf/

Formats a string using the standard fmt.Sprintf function.

语法

printf FORMAT INPUT

See the go doc for additional information.

1
2
{{ i18n ( printf "combined_%s" $var ) }}
{{ printf "formatted %.2f" 3.1416 }}

另请参阅

84 - println

将以下英文翻译为中文:

println

https://gohugo.io/functions/println/

Prints the default representation of the given argument using the standard fmt.Print function and enforces a linebreak.

语法

println INPUT

See the go doc for additional information. \n denotes the linebreak but isn’t printed in the templates as seen below:

1
{{ println "foo" }} → "foo\n"

另请参阅

85 - querify

将以下英文翻译为中文:

querify

https://gohugo.io/functions/querify/

Takes a set or slice of key-value pairs and returns a query string to be appended to URLs.

语法

querify KEY VALUE [KEY VALUE]...
querify COLLECTION

querify takes a set or slice of key-value pairs and returns a query string that can be appended to a URL.

The following examples create a link to a search results page on Google.

1
2
3
4
<a href="https://www.google.com?{{ (querify "q" "test" "page" 3) | safeURL }}">Search</a>

{{ $qs := slice "q" "test" "page" 3 }}
<a href="https://www.google.com?{{ (querify $qs) | safeURL }}">Search</a>

Both of these examples render the following HTML:

1
<a href="https://www.google.com?page=3&q=test">Search</a>

另请参阅

86 - range

将以下英文翻译为中文:

range

https://gohugo.io/functions/range/

Iterates over a map, array, or slice.

语法

range COLLECTION

Just like in the Go programming language, Go and Hugo templates make heavy use of range to iterate over a map, array or slice. Other templating languages use a foreach for the equivalent functionality.

range is fundamental to templating in Hugo. (See the Introduction to Hugo Templates for more examples.)

另请参阅

87 - readDir

将以下英文翻译为中文:

readDir

https://gohugo.io/functions/readdir/

Returns an array of FileInfo structures sorted by filename, one element for each directory entry.

语法

os.ReadDir PATH
readDir PATH

The os.ReadDir function resolves the path relative to the root of your project directory. A leading path separator (/) is optional.

With this directory structure:

1
2
3
4
5
6
content/
├── about.md
├── contact.md
└── news/
    ├── article-1.md
    └── article-2.md

This template code:

1
2
3
{{ range os.ReadDir "content" }}
  {{ .Name }} --> {{ .IsDir }}
{{ end }}

Produces:

1
2
3
about.md --> false
contact.md --> false
news --> true

Note that os.ReadDir is not recursive.

Details of the FileInfo structure are available in the Go documentation.

For more information on using readDir and readFile in your templates, see Local File Templates.

另请参阅

88 - readFile

将以下英文翻译为中文:

readFile

https://gohugo.io/functions/readfile/

Returns the contents of a file.

语法

os.ReadFile PATH
readFile PATH

The os.ReadFile function attempts to resolve the path relative to the root of your project directory. If a matching file is not found, it will attempt to resolve the path relative to the contentDir. A leading path separator (/) is optional.

With a file named README.md in the root of your project directory:

1
This is **bold** text.

This template code:

1
{{ os.ReadFile "README.md" }}

Produces:

1
This is **bold** text.

Note that os.ReadFile returns raw (uninterpreted) content.

For more information on using readDir and readFile in your templates, see Local File Templates.

另请参阅

89 - ref

将以下英文翻译为中文:

ref

https://gohugo.io/functions/ref/

Returns the absolute permalink to a page.

语法

ref . PAGE

This function takes two parameters:

  • The context of the page from which to resolve relative paths, typically the current page (.)
  • The path to a page, with or without a file extension, with or without an anchor. A path without a leading / is first resolved relative to the given context, then to the remainder of the site.
1
2
3
4
5
6
7
{{ ref . "about" }}
{{ ref . "about#anchor" }}
{{ ref . "about.md" }}
{{ ref . "about.md#anchor" }}
{{ ref . "#anchor" }}
{{ ref . "/blog/my-post" }}
{{ ref . "/blog/my-post.md" }}

To return the absolute permalink to another language version of a page:

1
{{ ref . (dict "path" "about.md" "lang" "fr") }}

To return the absolute permalink to another Output Format of a page:

1
{{ ref . (dict "path" "about.md" "outputFormat" "rss") }}

Hugo emits an error or warning if the page cannot be uniquely resolved. The error behavior is configurable; see Ref and RelRef Configuration.

This function is used by Hugo’s built-in ref shortcode. For a detailed explanation of how to leverage this shortcode for content management, see Links and Cross References.

另请参阅

90 - reflect.IsMap

将以下英文翻译为中文:

reflect.IsMap

https://gohugo.io/functions/reflect.ismap/

Reports if a value is a map.

语法

reflect.IsMap INPUT

reflect.IsMap reports if VALUE is a map. Returns a boolean.

1
2
{{ reflect.IsMap (dict "key" "value") }} → true
{{ reflect.IsMap "yo" }} → false

另请参阅

91 - reflect.IsSlice

将以下英文翻译为中文:

reflect.IsSlice

https://gohugo.io/functions/reflect.isslice/

Reports if a value is a slice.

语法

reflect.IsSlice INPUT

reflect.IsSlice reports if VALUE is a slice. Returns a boolean.

1
2
{{ reflect.IsSlice (slice 1 2 3) }} → true
{{ reflect.IsSlice "yo" }} → false

另请参阅

92 - relLangURL

将以下英文翻译为中文:

relLangURL

https://gohugo.io/functions/rellangurl/

Returns a relative URL with a language prefix, if any.

语法

relLangURL INPUT

Use this function with both monolingual and multilingual configurations. The URL returned by this function depends on:

  • Whether the input begins with a slash
  • The baseURL in site configuration
  • The language prefix, if any

In examples that follow, the project is multilingual with content in both Español (es) and English (en). The default language is Español. The returned values are from the English site.

Input does not begin with a slash

If the input does not begin with a slash, the resulting URL will be correct regardless of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ relLangURL "" }}           →   /en/
{{ relLangURL "articles" }}   →   /en/articles
{{ relLangURL "style.css" }}  →   /en/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ relLangURL "" }}           →   /docs/en/
{{ relLangURL "articles" }}   →   /docs/en/articles
{{ relLangURL "style.css" }}  →   /docs/en/style.css

Input begins with a slash

If the input begins with a slash, the resulting URL will be incorrect when the baseURL includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ relLangURL "/" }}          →   /en/
{{ relLangURL "/articles" }}  →   /en/articles
{{ relLangURL "/style.css" }} →   /en/style.css

With baseURL = https://example.org/docs/

1
2
3
{{ relLangURL "/" }}          →   /en/
{{ relLangURL "/articles" }}  →   /en/articles
{{ relLangURL "/style.css" }} →   /en/style.css

The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.

另请参阅

93 - relref

将以下英文翻译为中文:

relref

https://gohugo.io/functions/relref/

Returns the relative permalink to a page.

语法

relref . PAGE

This function takes two parameters:

  • The context of the page from which to resolve relative paths, typically the current page (.)
  • The path to a page, with or without a file extension, with or without an anchor. A path without a leading / is first resolved relative to the given context, then to the remainder of the site.
1
2
3
4
5
6
7
{{ relref . "about" }}
{{ relref . "about#anchor" }}
{{ relref . "about.md" }}
{{ relref . "about.md#anchor" }}
{{ relref . "#anchor" }}
{{ relref . "/blog/my-post" }}
{{ relref . "/blog/my-post.md" }}

The permalink returned is relative to the protocol+host portion of the baseURL specified in the site configuration. For example:

CodebaseURLPermalink
{{ relref . "/about" }}http://example.org//about/
{{ relref . "/about" }}http://example.org/x//x/about/

To return the relative permalink to another language version of a page:

1
{{ relref . (dict "path" "about.md" "lang" "fr") }}

To return the relative permalink to another Output Format of a page:

1
{{ relref . (dict "path" "about.md" "outputFormat" "rss") }}

Hugo emits an error or warning if the page cannot be uniquely resolved. The error behavior is configurable; see Ref and RelRef Configuration.

This function is used by Hugo’s built-in relref shortcode. For a detailed explanation of how to leverage this shortcode for content management, see Links and Cross References.

另请参阅

94 - relURL

将以下英文翻译为中文:

relURL

https://gohugo.io/functions/relurl/

Returns a relative URL.

语法

relURL INPUT

With multilingual configurations, use the relLangURL function instead. The URL returned by this function depends on:

  • Whether the input begins with a slash
  • The baseURL in site configuration

Input does not begin with a slash

If the input does not begin with a slash, the resulting URL will be correct regardless of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ relURL "" }}           →   /
{{ relURL "articles" }}   →   /articles
{{ relURL "style.css" }}  →   /style.css

With baseURL = https://example.org/docs/

1
2
3
{{ relURL "" }}           →   /docs/
{{ relURL "articles" }}   →   /docs/articles
{{ relURL "style.css" }}  →   /docs/style.css

Input begins with a slash

If the input begins with a slash, the resulting URL will be incorrect when the baseURL includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the baseURL.

With baseURL = https://example.org/

1
2
3
{{ relURL "/" }}          →   /
{{ relURL "/articles" }}  →   /articles
{{ relURL "style.css" }}  →   /style.css

With baseURL = https://example.org/docs/

1
2
3
{{ relURL "/" }}          →   /
{{ relURL "/articles" }}  →   /articles
{{ relURL "/style.css" }} →   /style.css

The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.

另请参阅

95 - replace

将以下英文翻译为中文:

replace

https://gohugo.io/functions/replace/

Replaces all occurrences of the search string with the replacement string.

语法

replace INPUT OLD NEW [LIMIT]
strings.Replace INPUT OLD NEW [LIMIT]

Replace returns a copy of INPUT with all occurrences of OLD replaced with NEW. The number of replacements can be limited with an optional LIMIT parameter.

`{{ replace "Batman and Robin" "Robin" "Catwoman" }}`
→ "Batman and Catwoman"

{{ replace "aabbaabb" "a" "z" 2 }} → "zzbbaabb"

96 - replaceRE

将以下英文翻译为中文:

replaceRE

https://gohugo.io/functions/replacere/

Returns a string, replacing all occurrences of a regular expression with a replacement pattern.

语法

replaceRE PATTERN REPLACEMENT INPUT [LIMIT]
strings.ReplaceRE PATTERN REPLACEMENT INPUT [LIMIT]

By default, replaceRE replaces all matches. You can limit the number of matches with an optional LIMIT parameter.

When specifying the regular expression, use a raw string literal (backticks) instead of an interpreted string literal (double quotes) to simplify the syntax. With an interpreted string literal you must escape backslashes.

This function uses the RE2 regular expression library. See the RE2 syntax documentation for details. Note that the RE2 \C escape sequence is not supported.

The RE2 syntax is a subset of that accepted by PCRE, roughly speaking, and with various caveats.

This example replaces two or more consecutive hyphens with a single hyphen:

1
2
{{ $s := "a-b--c---d" }}
{{ replaceRE `(-{2,})` "-" $s }} → a-b-c-d

To limit the number of replacements to one:

1
2
{{ $s := "a-b--c---d" }}
{{ replaceRE `(-{2,})` "-" $s 1 }} → a-b-c---d

You can use $1, $2, etc. within the replacement string to insert the groups captured within the regular expression:

1
2
{{ $s := "http://gohugo.io/docs" }}
{{ replaceRE "^https?://([^/]+).*" "$1" $s }} → gohugo.io

You can write and test your regular expression using regex101.com. Be sure to select the Go flavor before you begin.

另请参阅

97 - safeCSS

将以下英文翻译为中文:

safeCSS

https://gohugo.io/functions/safecss/

Declares the provided string as a known “safe” CSS string.

语法

safeCSS INPUT

In this context, safe means CSS content that matches any of the following:

  1. The CSS3 stylesheet production, such as p { color: purple }.
  2. The CSS3 rule production, such as a[href=~"https:"].foo#bar.
  3. CSS3 declaration productions, such as color: red; margin: 2px.
  4. The CSS3 value production, such as rgba(0, 0, 255, 127).

Example: Given style = "color: red;" defined in the front matter of your .md file:

  • <p style="{{ .Params.style | safeCSS }}">…</p><p style="color: red;">…</p>
  • <p style="{{ .Params.style }}">…</p><p style="ZgotmplZ">…</p>

“ZgotmplZ” is a special value that indicates that unsafe content reached a CSS or URL context.

另请参阅

98 - safeHTML

将以下英文翻译为中文:

safeHTML

https://gohugo.io/functions/safehtml/

Declares a provided string as a “safe” HTML document to avoid escaping by Go templates.

语法

safeHTML INPUT

It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.

Given a site-wide config.toml with the following copyright value:

config.

=== “yaml”

``` yaml
copyright: © 2015 Jane Doe.  <a href="https://creativecommons.org/licenses/by/4.0/">Some
  rights reserved</a>.
```

=== “toml”

``` toml
copyright = '© 2015 Jane Doe.  <a href="https://creativecommons.org/licenses/by/4.0/">Some rights reserved</a>.'
```

=== “json”

``` json
{
   "copyright": "© 2015 Jane Doe.  \u003ca href=\"https://creativecommons.org/licenses/by/4.0/\"\u003eSome rights reserved\u003c/a\u003e."
}
```

{{ .Site.Copyright | safeHTML }} in a template would then output:

1
© 2015 Jane Doe.  <a href="https://creativecommons.org/licenses/by/4.0/">Some rights reserved</a>.

However, without the safeHTML function, html/template assumes .Site.Copyright to be unsafe and therefore escapes all HTML tags and renders the whole string as plain text:

1
<p>© 2015 Jane Doe.  &lt;a href=&#34;https://creativecommons.org/licenses by/4.0/&#34;&gt;Some rights reserved&lt;/a&gt;.</p>

另请参阅

99 - safeHTMLAttr

将以下英文翻译为中文:

safeHTMLAttr

https://gohugo.io/functions/safehtmlattr/

Declares the provided string as a safe HTML attribute.

语法

safeHTMLAttr INPUT

Given a site configuration that contains this menu entry:

config.

=== “yaml”

``` yaml
menu:
  main:
  - name: IRC
    url: irc://irc.freenode.net/#golang
```

=== “toml”

``` toml
[menu]
[[menu.main]]
  name = 'IRC'
  url = 'irc://irc.freenode.net/#golang'
```

=== “json”

``` json
{
   "menu": {
      "main": [
         {
            "name": "IRC",
            "url": "irc://irc.freenode.net/#golang"
         }
      ]
   }
}
```

Attempting to use the url value directly in an attribute:

1
2
3
{{ range site.Menus.main }}
  <a href="{{ .URL }}">{{ .Name }}</a>
{{ end }}

Will produce:

1
<a href="#ZgotmplZ">IRC</a>

ZgotmplZ is a special value, inserted by Go’s template/html package, that indicates that unsafe content reached a CSS or URL context.

To override the safety check, use the safeHTMLAttr function:

1
2
3
{{ range site.Menus.main }}
  <a {{ printf "href=%q" .URL | safeHTMLAttr }}>{{ .Name }}</a>
{{ end }}

另请参阅

100 - safeJS

将以下英文翻译为中文:

safeJS

https://gohugo.io/functions/safejs/

Declares the provided string as a known safe JavaScript string.

语法

safeJS INPUT

In this context, safe means the string encapsulates a known safe EcmaScript5 Expression (e.g., (x + y * z())).

Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like { foo:bar() }\n['foo'](), which is both a valid expression and a valid program with a very different meaning.

Example: Given hash = "619c16f" defined in the front matter of your .md file:

  • <script>var form_{{ .Params.hash | safeJS }};…</script><script>var form_619c16f;…</script>
  • <script>var form_{{ .Params.hash }};…</script><script>var form_"619c16f";…</script>

另请参阅

101 - safeURL

将以下英文翻译为中文:

safeURL

https://gohugo.io/functions/safeurl/

Declares the provided string as a safe URL or URL substring.

语法

safeURL INPUT

safeURL declares the provided string as a “safe” URL or URL substring (see RFC 3986). A URL like javascript:checkThatFormNotEditedBeforeLeavingPage() from a trusted source should go in the page, but by default dynamic javascript: URLs are filtered out since they are a frequently exploited injection vector.

Without safeURL, only the URI schemes http:, https: and mailto: are considered safe by Go templates. If any other URI schemes (e.g., irc: and javascript:) are detected, the whole URL will be replaced with #ZgotmplZ. This is to “defang” any potential attack in the URL by rendering it useless.

The following examples use a site config.toml with the following menu entry:

config.

=== “yaml”

``` yaml
menu:
  main:
  - name: 'IRC: #golang at freenode'
    url: irc://irc.freenode.net/#golang
```

=== “toml”

``` toml
[menu]
[[menu.main]]
  name = 'IRC: #golang at freenode'
  url = 'irc://irc.freenode.net/#golang'
```

=== “json”

``` json
{
   "menu": {
      "main": [
         {
            "name": "IRC: #golang at freenode",
            "url": "irc://irc.freenode.net/#golang"
         }
      ]
   }
}
```

The following is an example of a sidebar partial that may be used in conjunction with the preceding front matter example:

layouts/partials/bad-url-sidebar-menu.html

1
2
3
4
5
6
<!-- This unordered list may be part of a sidebar menu -->
<ul>
  {{ range .Site.Menus.main }}
    <li><a href="{{ .URL }}">{{ .Name }}</a></li>
  {{ end }}
</ul>

This partial would produce the following HTML output:

1
2
3
4
<!-- This unordered list may be part of a sidebar menu -->
<ul>
  <li><a href="#ZgotmplZ">IRC: #golang at freenode</a></li>
</ul>

The odd output can be remedied by adding | safeURL to our .URL page variable:

layouts/partials/correct-url-sidebar-menu.html

1
2
3
4
<!-- This unordered list may be part of a sidebar menu -->
<ul>
    <li><a href="{{ .URL | safeURL }}">{{ .Name }}</a></li>
</ul>

With the .URL page variable piped through safeURL, we get the desired output:

1
2
3
<ul class="sidebar-menu">
  <li><a href="irc://irc.freenode.net/#golang">IRC: #golang at freenode</a></li>
</ul>

另请参阅

102 - seq

将以下英文翻译为中文:

seq

https://gohugo.io/functions/seq/

Returns a slice of integers.

语法

seq LAST
seq FIRST LAST
seq FIRST INCREMENT LAST
{{ seq 2 }} → [1 2]
{{ seq 0 2 }} → [0 1 2]
{{ seq -2 2 }} → [-2 -1 0 1 2]
{{ seq -2 2 2 }} → [-2 0 2]

Iterate over a sequence of integers:

1
2
3
4
5
{{ $product := 1 }}
{{ range seq 4 }}
  {{ $product = mul $product . }}
{{ end }}
{{ $product }} → 24

103 - sha

将以下英文翻译为中文:

sha

https://gohugo.io/functions/sha/

Hashes the given input and returns either an SHA1 or SHA256 checksum.

语法

sha1 INPUT
sha256 INPUT

sha1 hashes the given input and returns its SHA1 checksum.

1
2
{{ sha1 "Hello world, gophers!" }}
<!-- returns the string "c8b5b0e33d408246e30f53e32b8f7627a7a649d4" -->

sha256 hashes the given input and returns its SHA256 checksum.

1
2
{{ sha256 "Hello world, gophers!" }}
<!-- returns the string "6ec43b78da9669f50e4e422575c54bf87536954ccd58280219c393f2ce352b46" -->

另请参阅

104 - shuffle

将以下英文翻译为中文:

shuffle

https://gohugo.io/functions/shuffle/

Returns a random permutation of a given array or slice.

语法

shuffle COLLECTION
{{ shuffle (seq 1 2 3) }} → [3 1 2] 
{{ shuffle (slice "a" "b" "c") }} → [b a c] 

The result will vary from one build to the next.

另请参阅

105 - singularize

将以下英文翻译为中文:

singularize

https://gohugo.io/functions/singularize/

Converts a word according to a set of common English singularization rules.

语法

singularize INPUT

{{ "cats" | singularize }} → “cat”

See also the .Data.Singular taxonomy variable for singularizing taxonomy names.

另请参阅

106 - site

将以下英文翻译为中文:

site

https://gohugo.io/functions/site/

The site function provides global access to the same data as the .Site page method.

语法

site

site is a global function which returns the same data as the .Site page method. See: Site Variables.

107 - slice

将以下英文翻译为中文:

slice

https://gohugo.io/functions/slice/

Creates a slice (array) of all passed arguments.

语法

slice ITEM...

One use case is the concatenation of elements in combination with the delimit function:

slice.html

1
2
3
4
{{ $sliceOfStrings := slice "foo" "bar" "buzz" }}
<!-- returns the slice [ "foo", "bar", "buzz"] -->
{{ delimit ($sliceOfStrings) ", " }}
<!-- returns the string "foo, bar, buzz" -->

108 - slicestr

将以下英文翻译为中文:

slicestr

https://gohugo.io/functions/slicestr/

Creates a slice of a half-open range, including start and end indices.

语法

slicestr STRING START [END]
strings.SliceString STRING START [END]

For example, 1 and 4 creates a slice including elements 1 through 3. The end index can be omitted; it defaults to the string’s length.

  • {{ slicestr "BatMan" 3 }} → “Man”
  • {{ slicestr "BatMan" 0 3 }} → “Bat”

另请参阅

109 - sort

将以下英文翻译为中文:

sort

https://gohugo.io/functions/sort/

Sorts slices, maps, and page collections.

语法

sort COLLECTION [KEY] [ORDER]

The KEY is optional when sorting slices in ascending order, otherwise it is required. When sorting slices, use the literal value in place of the KEY. See examples below.

The ORDER may be either asc (ascending) or desc (descending). The default sort order is ascending.

Sort a slice

The examples below assume this site configuration:

config.

=== “yaml”

``` yaml
params:
  grades:
  - b
  - a
  - c
```

=== “toml”

``` toml
[params]
  grades = ['b', 'a', 'c']
```

=== “json”

``` json
{
   "params": {
      "grades": [
         "b",
         "a",
         "c"
      ]
   }
}
```

Ascending order

Sort slice elements in ascending order using either of these constructs:

layouts/_default/single.html

1
2
{{ sort site.Params.grades }} → [a b c]
{{ sort site.Params.grades "value" "asc" }} → [a b c]

In the examples above, value is the KEY representing the value of the slice element.

Descending order

Sort slice elements in descending order:

layouts/_default/single.html

1
{{ sort site.Params.grades "value" "desc" }} → [c b a]

In the example above, value is the KEY representing the value of the slice element.

Sort a map

The examples below assume this site configuration:

config.

=== “yaml”

``` yaml
params:
  authors:
    a:
      firstName: Marius
      lastName: Pontmercy
    b:
      firstName: Victor
      lastName: Hugo
    c:
      firstName: Jean
      lastName: Valjean
```

=== “toml”

``` toml
[params]
  [params.authors]
    [params.authors.a]
      firstName = 'Marius'
      lastName = 'Pontmercy'
    [params.authors.b]
      firstName = 'Victor'
      lastName = 'Hugo'
    [params.authors.c]
      firstName = 'Jean'
      lastName = 'Valjean'
```

=== “json”

``` json
{
   "params": {
      "authors": {
         "a": {
            "firstName": "Marius",
            "lastName": "Pontmercy"
         },
         "b": {
            "firstName": "Victor",
            "lastName": "Hugo"
         },
         "c": {
            "firstName": "Jean",
            "lastName": "Valjean"
         }
      }
   }
}
```

When sorting maps, the KEY argument must be lowercase.

Ascending order

Sort map objects in ascending order using either of these constructs:

layouts/_default/single.html

1
2
3
4
5
6
7
{{ range sort site.Params.authors "firstname" }}
  {{ .firstName }}
{{ end }}

{{ range sort site.Params.authors "firstname" "asc" }}
  {{ .firstName }}
{{ end }}

These produce:

1
Jean Marius Victor

Descending order

Sort map objects in descending order:

layouts/_default/single.html

1
2
3
{{ range sort site.Params.authors "firstname" "desc" }}
  {{ .firstName }}
{{ end }}

This produces:

1
Victor Marius Jean

Sort a page collection

Although you can use the sort function to sort a page collection, Hugo provides built-in methods for sorting page collections by:

  • weight
  • linktitle
  • title
  • front matter parameter
  • date
  • expiration date
  • last modified date
  • publish date
  • length

In this contrived example, sort the site’s regular pages by .Type in descending order:

layouts/_default/home.html

1
2
3
{{ range sort site.RegularPages "Type" "desc" }}
  <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }}

另请参阅

110 - split

将以下英文翻译为中文:

split

https://gohugo.io/functions/split/

Returns a slice of strings by splitting STRING by DELIM.

语法

split STRING DELIM

Examples:

1
2
{{ split "tag1,tag2,tag3" "," }} → ["tag1", "tag2", "tag3"]
{{ split "abc" "" }} → ["a", "b", "c"]

split essentially does the opposite of delimit. While split creates a slice from a string, delimit creates a string from a slice.

另请参阅

111 - string

将以下英文翻译为中文:

string

https://gohugo.io/functions/string/

Cast a value to a string.

语法

string INPUT

With a decimal (base 10) input:

1
2
3
4
5
6
7
8
{{ string 11 }} → 11 (string)
{{ string "11" }} → 11 (string)

{{ string 11.1 }} → 11.1 (string)
{{ string "11.1" }} → 11.1 (string)

{{ string 11.9 }} → 11.9 (string)
{{ string "11.9" }} → 11.9 (string)

With a binary (base 2) input:

1
2
{{ string 0b11 }} → 3 (string)
{{ string "0b11" }} → 0b11 (string)

With an octal (base 8) input (use either notation):

1
2
3
4
5
{{ string 011 }} → 9 (string)
{{ string "011" }} → 011 (string)

{{ string 0o11 }} → 9 (string)
{{ string "0o11" }} → 0o11 (string)

With a hexadecimal (base 16) input:

1
2
{{ string 0x11 }} → 17 (string)
{{ string "0x11" }} → 0x11 (string)

另请参阅

112 - strings.Contains

将以下英文翻译为中文:

strings.Contains

https://gohugo.io/functions/strings.contains/

Reports whether a string contains a substring.

语法

strings.Contains STRING SUBSTRING
{{ strings.Contains "Hugo" "go" }} → true

The check is case sensitive:

{{ strings.Contains "Hugo" "Go" }} → false

113 - strings.ContainsAny

将以下英文翻译为中文:

strings.ContainsAny

https://gohugo.io/functions/strings.containsany/

Reports whether a string contains any character from a given string.

语法

strings.ContainsAny STRING CHARACTERS
{{ strings.ContainsAny "Hugo" "gm" }} → true

The check is case sensitive:

{{ strings.ContainsAny "Hugo" "Gm" }} → false

114 - strings.Count

将以下英文翻译为中文:

strings.Count

https://gohugo.io/functions/strings.count/

Returns the number of non-overlapping instances of a substring within a string.

语法

strings.Count SUBSTR STRING

If SUBSTR is an empty string, this function returns 1 plus the number of Unicode code points in STRING.

ExampleResult
`{{ “aaabaab”strings.Count “a” }}`
`{{ “aaabaab”strings.Count “aa” }}`
`{{ “aaabaab”strings.Count “aaa” }}`
`{{ “aaabaab”strings.Count "" }}`

另请参阅

115 - strings.FirstUpper

将以下英文翻译为中文:

strings.FirstUpper

https://gohugo.io/functions/strings.firstupper/

Capitalizes the first character of a given string.

语法

strings.FirstUpper STRING
{{ strings.FirstUpper "foo" }} → "Foo"

116 - strings.HasPrefix

将以下英文翻译为中文:

strings.HasPrefix

https://gohugo.io/functions/strings.hasprefix/

Tests whether a string begins with prefix.

语法

hasPrefix STRING PREFIX
strings.HasPrefix STRING PREFIX
{{ hasPrefix "Hugo" "Hu" }} → true

另请参阅

117 - strings.HasSuffix

将以下英文翻译为中文:

strings.HasSuffix

https://gohugo.io/functions/strings.hassuffix/

Tests whether a string ends with suffix.

语法

hasSuffix STRING SUFFIX
strings.HasSuffix STRING SUFFIX
{{ hasSuffix "Hugo" "go" }} → true

另请参阅

118 - strings.Repeat

将以下英文翻译为中文:

strings.Repeat

https://gohugo.io/functions/strings.repeat/

Returns INPUT repeated COUNT times.

语法

strings.Repeat COUNT INPUT
{{ strings.Repeat 3 "yo" }} → "yoyoyo"
{{ "yo" | strings.Repeat 3 }} → "yoyoyo"

另请参阅

119 - strings.RuneCount

将以下英文翻译为中文:

strings.RuneCount

https://gohugo.io/functions/strings.runecount/

Determines the number of runes in a string.

语法

strings.RuneCount INPUT

In contrast with strings.CountRunes function, which strips HTML and whitespace before counting runes, strings.RuneCount simply counts all the runes in a string. It relies on the Go [utf8.RuneCountInString] function.

1
2
{{ "Hello, 世界" | strings.RuneCount }}
<!-- outputs a content length of 9 runes. -->

另请参阅

120 - strings.TrimLeft

将以下英文翻译为中文:

strings.TrimLeft

https://gohugo.io/functions/strings.trimleft/

Returns a slice of a given string with all leading characters contained in the cutset removed.

语法

strings.TrimLeft CUTSET STRING

Given the string "abba", leading "a"’s can be removed a follows:

{{ strings.TrimLeft "a" "abba" }} → "bba"

Numbers can be handled as well:

{{ strings.TrimLeft 12 1221341221 }} → "341221"

另请参阅

121 - strings.TrimPrefix

将以下英文翻译为中文:

strings.TrimPrefix

https://gohugo.io/functions/strings.trimprefix/

Returns a given string s without the provided leading prefix string. If s doesn’t start with prefix, s is returned unchanged.

语法

strings.TrimPrefix PREFIX STRING

Given the string "aabbaa", the specified prefix is only removed if "aabbaa" starts with it:

{{ strings.TrimPrefix "a" "aabbaa" }} → "abbaa"
{{ strings.TrimPrefix "aa" "aabbaa" }} → "bbaa"
{{ strings.TrimPrefix "aaa" "aabbaa" }} → "aabbaa"

另请参阅

122 - strings.TrimRight

将以下英文翻译为中文:

strings.TrimRight

https://gohugo.io/functions/strings.trimright/

Returns a slice of a given string with all trailing characters contained in the cutset removed.

语法

strings.TrimRight CUTSET STRING

Given the string "abba", trailing "a"’s can be removed a follows:

{{ strings.TrimRight "a" "abba" }} → "abb"

Numbers can be handled as well:

{{ strings.TrimRight 12 1221341221 }} → "122134"

另请参阅

123 - strings.TrimSuffix

将以下英文翻译为中文:

strings.TrimSuffix

https://gohugo.io/functions/strings.trimsuffix/

Returns a given string s without the provided trailing suffix string. If s doesn’t end with suffix, s is returned unchanged.

语法

strings.TrimSuffix SUFFIX STRING

Given the string "aabbaa", the specified suffix is only removed if "aabbaa" ends with it:

{{ strings.TrimSuffix "a" "aabbaa" }} → "aabba"
{{ strings.TrimSuffix "aa" "aabbaa" }} → "aabb"
{{ strings.TrimSuffix "aaa" "aabbaa" }} → "aabbaa"

另请参阅

124 - substr

将以下英文翻译为中文:

substr

https://gohugo.io/functions/substr/

Extracts parts of a string from a specified character’s position and returns the specified number of characters.

语法

substr STRING START [LENGTH]
strings.Substr STRING START [LENGTH]

It normally takes two parameters: start and length. It can also take one parameter: start, i.e. length is omitted, in which case the substring starting from start until the end of the string will be returned.

To extract characters from the end of the string, use a negative start number.

If length is given and is negative, that number of characters will be omitted from the end of string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{{ substr "abcdef" 0 }} → "abcdef"
{{ substr "abcdef" 1 }} → "bcdef"

{{ substr "abcdef" 0 1 }} → "a"
{{ substr "abcdef" 1 1 }} → "b"

{{ substr "abcdef" 0 -1 }} → "abcde"
{{ substr "abcdef" 1 -1 }} → "bcde"

{{ substr "abcdef" -1 }} → "f"
{{ substr "abcdef" -2 }} → "ef"

{{ substr "abcdef" -1 1 }} → "f"
{{ substr "abcdef" -2 1 }} → "e"

{{ substr "abcdef" -3 -1 }} → "de"
{{ substr "abcdef" -3 -2 }} → "d"

另请参阅

125 - symdiff

将以下英文翻译为中文:

symdiff

https://gohugo.io/functions/symdiff/

collections.SymDiff (alias symdiff) returns the symmetric difference of two collections.

语法

COLLECTION | symdiff COLLECTION

Example:

1
{{ slice 1 2 3 | symdiff (slice 3 4) }}

The above will print [1 2 4].

Also see https://en.wikipedia.org/wiki/Symmetric_difference

另请参阅

126 - templates.Exists

将以下英文翻译为中文:

templates.Exists

https://gohugo.io/functions/templates.exists/

Checks whether a template file exists under the given path relative to the layouts directory.

语法

templates.Exists PATH

A template file is any file living below the layouts directories of either the project or any of its theme components including partials and shortcodes.

The function is particularly handy with dynamic path. The following example ensures the build will not break on a .Type missing its dedicated header partial.

1
2
3
4
5
6
{{ $partialPath := printf "headers/%s.html" .Type }}
{{ if templates.Exists ( printf "partials/%s" $partialPath ) }}
  {{ partial $partialPath . }}
{{ else }}
  {{ partial "headers/default.html" . }}
{{ end }}

另请参阅

127 - time

将以下英文翻译为中文:

time

https://gohugo.io/functions/time/

Converts a timestamp string into a time.Time structure.

语法

time INPUT [TIMEZONE]

time converts a timestamp string with an optional default location into a time.Time structure so you can access its fields:

1
2
3
{{ time "2016-05-28" }} → "2016-05-28T00:00:00Z"
{{ (time "2016-05-28").YearDay }} → 149
{{ mul 1000 (time "2016-05-28T10:30:00.00+10:00").Unix }} → 1464395400000, or Unix time in milliseconds

Using Locations

The optional TIMEZONE parameter is a string that sets a default time zone (or more specific, the location, which represents the collection of time offsets in a geographical area) that is associated with the specified time value. If the time value has an explicit timezone or offset specified, it will take precedence over the TIMEZONE parameter.

The list of valid locations may be system dependent, but should include UTC, Local, or any location in the IANA Time Zone database.

If no TIMEZONE is set, the timeZone from site configuration will be used.

1
2
3
{{ time "2020-10-20" }} → 2020-10-20 00:00:00 +0000 UTC
{{ time "2020-10-20" "America/Los_Angeles" }} → 2020-10-20 00:00:00 -0700 PDT
{{ time "2020-01-20" "America/Los_Angeles" }} → 2020-01-20 00:00:00 -0800 PST

Example: Using time to get Month Index

The following example takes a UNIX timestamp—set as utimestamp: "1489276800" in a content’s front matter—converts the timestamp (string) to an integer using the int function, and then uses printf to convert the Month property of time into an index.

The following example may be useful when setting up multilingual sites:

unix-to-month-integer.html

1
2
3
4
5
6
{{ $time := time (int .Params.addDate)}}
=> $time = 1489276800
{{ $time.Month }}
=> "March"
{{ $monthindex := printf "%d" $time.Month }}
=> $monthindex = 3

另请参阅

128 - time.Format

将以下英文翻译为中文:

time.Format

https://gohugo.io/functions/dateformat/

Converts a date/time to a localized string.

语法

time.Format LAYOUT INPUT
dateFormat LAYOUT INPUT

time.Format (alias dateFormat) converts either a time.Time object (e.g. .Date) or a timestamp string INPUT into the format specified by the LAYOUT string.

1
{{ time.Format "Monday, Jan 2, 2006" "2015-01-21" }} → "Wednesday, Jan 21, 2015"

time.Format returns a localized string for the current language.

The LAYOUT string can be either:

  • Go’s Layout String to learn about how the LAYOUT string has to be formatted. There are also some useful examples.
  • A custom Hugo layout identifier (see full list below)

See the time function to convert a timestamp string to a Go time.Time type value.

Date/time formatting layouts

Go’s date layout strings can be hard to reason about, especially with multiple languages. You can alternatively use some predefined layout identifiers that will output localized dates or times:

1
{{ .Date | time.Format ":date_long" }}

The full list of custom layouts with examples for English:

  • :date_full => Wednesday, June 6, 2018
  • :date_long => June 6, 2018
  • :date_medium => Jun 6, 2018
  • :date_short => 6/6/18
  • :time_full => 2:09:37 am UTC
  • :time_long => 2:09:37 am UTC
  • :time_medium => 2:09:37 am
  • :time_short => 2:09 am

另请参阅

129 - time.ParseDuration

将以下英文翻译为中文:

time.ParseDuration

https://gohugo.io/functions/time.parseduration/

Parses a given duration string into a time.Duration structure.

语法

time.ParseDuration DURATION

time.ParseDuration parses a duration string into a time.Duration structure so you can access its fields. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as 300ms, -1.5h or 2h45m. Valid time units are ns, us (or µs), ms, s, m, h.

You can perform time operations on the returned time.Duration value:

{{ printf "There are %.0f seconds in one day." (time.ParseDuration "24h").Seconds }}
<!-- Output: There are 86400 seconds in one day. -->

130 - title

将以下英文翻译为中文:

title

https://gohugo.io/functions/title/

​ 将提供的字符串转换为标题大小写样式。

语法

title STRING
strings.Title STRING
{{ title "table of contents (TOC)" }} → "Table of Contents (TOC)"

​ 默认情况下,Hugo 遵循美联社风格指南(Associated Press (AP) Stylebook)的大写规则。如果您更喜欢遵循芝加哥手册风格(Chicago Manual of Style),或者使用 Go 的惯例将每个单词都大写,请更改您的站点配置

另请参阅

131 - transform.Unmarshal

将以下英文翻译为中文:

transform.Unmarshal

https://gohugo.io/functions/transform.unmarshal/

transform.Unmarshal (alias unmarshal) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV.

语法

RESOURCE or STRING | transform.Unmarshal [OPTIONS]

The function accepts either a Resource created in Hugo Pipes or via Page Bundles, or simply a string. The two examples below will produce the same map:

1
2
{{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}`
{{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }}

In both the above examples, you get a map you can work with:

1
{{ $greetings.hello }}

The above prints Hello Hugo.

CSV Options

Unmarshal with CSV as input has some options you can set:

  • delimiter

    The delimiter used, default is ,.

  • comment

    The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.:

Example:

1
{{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }}

XML data

As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data.

To get the contents of <title> in the document below, you use {{ .message.title }}:

1
2
3
4
5
6
<root>
    <message>
        <title>Hugo rocks!</title>
        <description>Thanks for using Hugo</description>
    </message>
</root>

The following example lists the items of an RSS feed:

1
2
3
4
5
6
7
8
9
{{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }}
    {{ range .channel.item }}
        <strong>{{ .title | plainify | htmlUnescape }}</strong><br />
        <p>{{ .description | plainify | htmlUnescape }}</p>
        {{ $link := .link | plainify | htmlUnescape }}
        <a href="{{ $link }}">{{ $link }}</a><br />
        <hr>
    {{ end }}
{{ end }}

132 - trim

将以下英文翻译为中文:

trim

https://gohugo.io/functions/trim/

Returns a slice of a passed string with all leading and trailing characters from cutset removed.

语法

trim INPUT CUTSET
strings.Trim INPUT CUTSET
{{ trim "++Batman--" "+-" }} → "Batman"

trim requires the second argument, which tells the function specifically what to remove from the first argument. There is no default value for the second argument, so the following usage will not work:

1
{{ trim .Inner }}

Instead, the following example tells trim to remove extra new lines from the content contained in the shortcode .Inner variable:

1
{{ trim .Inner "\n" }}

Go templates also provide a simple method for trimming whitespace from either side of a Go tag by including a hyphen (-).

另请参阅

133 - truncate

将以下英文翻译为中文:

truncate

https://gohugo.io/functions/truncate/

Truncates a text to a max length without cutting words or leaving unclosed HTML tags.

语法

truncate SIZE [ELLIPSIS] INPUT
strings.Truncate SIZE [ELLIPSIS] INPUT

Since Go templates are HTML-aware, truncate will intelligently handle normal strings vs HTML strings:

1
{{ "<em>Keep my HTML</em>" | safeHTML | truncate 10 }}` → <em>Keep my …</em>`

If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the safeHTML template function before sending the value to truncate. Otherwise, the HTML tags will be escaped when passed through the truncate function.

另请参阅

134 - union

将以下英文翻译为中文:

union

https://gohugo.io/functions/union/

Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices.

语法

union SET1 SET2

Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both. The elements supported are strings, integers, and floats (only float64).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{ union (slice 1 2 3) (slice 3 4 5) }}
<!-- returns [1 2 3 4 5] -->

{{ union (slice 1 2 3) nil }}
<!-- returns [1 2 3] -->

{{ union nil (slice 1 2 3) }}
<!-- returns [1 2 3] -->

{{ union nil nil }}
<!-- returns an error because both arrays/slices have to be of the same type -->

OR filter in where query

This is also very useful to use as OR filters when combined with where:

1
2
3
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages = $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages = $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}

The above fetches regular pages not of page or about type unless they are pinned. And finally, we exclude all pages with no images set in Page params.

See intersect for AND.

另请参阅

135 - uniq

将以下英文翻译为中文:

uniq

https://gohugo.io/functions/uniq/

Takes in a slice or array and returns a slice with duplicate elements removed.

语法

uniq SET
{{ slice 1 3 2 1 | uniq }} --> [1 3 2]

另请参阅

136 - upper

将以下英文翻译为中文:

upper

https://gohugo.io/functions/upper/

Converts all characters in a string to uppercase

语法

upper INPUT
strings.ToUpper INPUT

Note that upper can be applied in your templates in more than one way:

1
2
{{ upper "BatMan" }} → "BATMAN"
{{ "BatMan" | upper }} → "BATMAN"

137 - urlize

将以下英文翻译为中文:

urlize

https://gohugo.io/functions/urlize/

Takes a string, sanitizes it for usage in URLs, and converts spaces to hyphens.

语法

urlize INPUT

The following examples pull from a content file with the following front matter:

xxxxxxxxxx2 1{{ upper “BatMan” }} → “BATMAN"2{{ “BatMan” | upper }} → “BATMAN"go-html-template

=== “yaml”

``` yaml
---
location: Chicago IL
tags:
- pizza
- beer
- hot dogs
title: The World's Greatest City
---
```

=== “toml”

``` toml
+++
location = 'Chicago IL'
tags = ['pizza', 'beer', 'hot dogs']
title = "The World's Greatest City"
+++
```

=== “json”

``` json
{
   "location": "Chicago IL",
   "tags": [
      "pizza",
      "beer",
      "hot dogs"
   ],
   "title": "The World's Greatest City"
}
```

The following might be used as a partial within a single page template:

layouts/partials/content-header.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<header>
    <h1>{{ .Title }}</h1>
    {{ with .Params.location }}
        <div><a href="/locations/{{ . | urlize }}">{{ . }}</a></div>
    {{ end }}
    <!-- Creates a list of tags for the content and links to each of their pages -->
    {{ with .Params.tags }}
    <ul>
        {{ range .}}
            <li>
                <a href="/tags/{{ . | urlize }}">{{ . }}</a>
            </li>
        {{ end }}
    </ul>
    {{ end }}
</header>

The preceding partial would then output to the rendered page as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<header>
  <h1>The World&#39;s Greatest City</h1>
  <div><a href="/locations/chicago-il">Chicago IL</a></div>
  <ul>
    <li>
      <a href="/tags/pizza">pizza</a>
    </li>
    <li>
      <a href="/tags/beer">beer</a>
    </li>
    <li>
      <a href="/tags/hot-dogs">hot dogs</a>
    </li>
  </ul>
</header>

另请参阅

138 - urlquery

将以下英文翻译为中文:

urlquery

https://gohugo.io/functions/urlquery/

Returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.

语法

urlquery INPUT [INPUT]...

This template code:

1
2
{{ $u := urlquery "https://" "example.com" | safeURL }}
<a href="https://example.org?url={{ $u }}">Link</a>

Is rendered to:

1
<a href="https://example.org?url=https%3A%2F%2Fexample.com">Link</a>

另请参阅

139 - urls.Parse

将以下英文翻译为中文:

urls.Parse

https://gohugo.io/functions/urls.parse/

Parses a URL into a URL structure.

语法

urls.Parse URL

The urls.Parse function parses a URL into a URL structure. The URL may be relative (a path, without a host) or absolute (starting with a scheme). Hugo throws an error when parsing an invalid URL.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{{ $url := "https://example.org:123/foo?a=6&b=7#bar" }}
{{ $u := urls.Parse $url }}

{{ $u.IsAbs }} → true
{{ $u.Scheme }} → https
{{ $u.Host }} → example.org:123
{{ $u.Hostname }} → example.org
{{ $u.RequestURI }} → /foo?a=6&b=7
{{ $u.Path }} → /foo
{{ $u.Query }} → map[a:[6] b:[7]]
{{ $u.Query.a }} → [6]
{{ $u.Query.Get "a" }} → 6
{{ $u.Query.Has "b" }} → true
{{ $u.Fragment }} → bar

另请参阅

140 - where

将以下英文翻译为中文:

where

https://gohugo.io/functions/where/

Filters an array to only the elements containing a matching value for a given field.

语法

where COLLECTION KEY [OPERATOR] MATCH

where filters an array to only the elements containing a matching value for a given field.

It works in a similar manner to the where keyword in SQL.

1
2
3
{{ range where .Pages "Section" "foo" }}
  {{ .Content }}
{{ end }}

It can be used by dot-chaining the second argument to refer to a nested element of a value.

content/example.md

=== “yaml”

``` yaml
---
series: golang
title: Example
---
```

=== “toml”

``` toml
+++
series = 'golang'
title = 'Example'
+++
```

=== “json”

``` json
{
   "series": "golang",
   "title": "Example"
}
```
1
2
3
{{ range where .Site.Pages "Params.series" "golang" }}
   {{ .Content }}
{{ end }}

It can also be used with the logical operators !=, >=, in, etc. Without an operator, where compares a given field with a matching value equivalent to =.

1
2
3
{{ range where .Pages "Section" "!=" "foo" }}
   {{ .Content }}
{{ end }}

The following logical operators are available with where:

  • =, ==, eq

    true if a given field value equals a matching value

  • !=, <>, ne

    true if a given field value doesn’t equal a matching value

  • >=, ge

    true if a given field value is greater than or equal to a matching value

  • >, gt

    true if a given field value is greater than a matching value

  • <=, le

    true if a given field value is lesser than or equal to a matching value

  • <, lt

    true if a given field value is lesser than a matching value

  • in

    true if a given field value is included in a matching value; a matching value must be an array or a slice

  • not in

    true if a given field value isn’t included in a matching value; a matching value must be an array or a slice

  • intersect

    true if a given field value that is a slice/array of strings or integers contains elements in common with the matching value; it follows the same rules as the intersect function.

Use where with Booleans

When using booleans you should not put quotation marks.

1
2
3
{{ range where .Pages "Draft" true }}
        <p>{{ .Title }}</p>
{{ end }}

Use where with intersect

1
2
3
4
5
{{ range where .Site.Pages "Params.tags" "intersect" .Params.tags }}
  {{ if ne .Permalink $.Permalink }}
    {{ .Render "summary" }}
  {{ end }}
{{ end }}

You can also put the returned value of the where clauses into a variable:

where-intersect-variables.html

1
2
3
4
5
{{ $v1 := where .Site.Pages "Params.a" "v1" }}
{{ $v2 := where .Site.Pages "Params.b" "v2" }}
{{ $filtered := $v1 | intersect $v2 }}
{{ range $filtered }}
{{ end }}

Use where with first

Using first and where together can be very powerful. Below snippet gets a list of posts only from main sections, sorts it using the default ordering for lists (i.e., weight => date), and then ranges through only the first 5 posts in that list:

first-and-where-together.html

1
2
3
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections) }}
   {{ .Content }}
{{ end }}

Nest where Clauses

You can also nest where clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the “blog” section and then ranges through the result of the first where clause and finds all pages that are not featured:

1
{{ range where (where .Pages "Section" "blog" ) "Params.featured" "!=" true }}

Unset Fields

Filtering only works for set fields. To check whether a field is set or exists, you can use the operand nil.

This can be useful to filter a small amount of pages from a large pool. Instead of setting a field on all pages, you can set that field on required pages only.

Only the following operators are available for nil

  • =, ==, eq: True if the given field is not set.
  • !=, <>, ne: True if the given field is set.
1
2
3
{{ range where .Pages "Params.specialpost" "!=" nil }}
   {{ .Content }}
{{ end }}

Portable where filters – site.Params.mainSections

This is especially important for themes.

To list the most relevant pages on the front page or similar, you should use the site.Params.mainSections list instead of comparing section names to hard-coded values like "posts" or "post".

1
{{ $pages := where site.RegularPages "Type" "in" site.Params.mainSections }}

If the user has not set this config parameter in their site config, it will default to the section with the most pages.

The user can override the default:

config.

=== “yaml”

``` yaml
params:
  mainSections:
  - blog
  - docs
```

=== “toml”

``` toml
[params]
  mainSections = ['blog', 'docs']
```

=== “json”

``` json
{
   "params": {
      "mainSections": [
         "blog",
         "docs"
      ]
   }
}
```

141 - with

将以下英文翻译为中文:

with

https://gohugo.io/functions/with/

Rebinds the context (.) within its scope and skips the block if the variable is absent or empty.

语法

with INPUT

An alternative way of writing an if statement and then referencing the same value is to use with instead. with rebinds the context (.) within its scope and skips the block if the variable is absent, unset or empty.

The set of empty values is defined by the Go templates package. Empty values include false, the number zero, and the empty string.

If you want to render a block if an index or key is present in a slice, array, channel or map, regardless of whether the value is empty, you should use isset instead.

The following example checks for a user-defined site variable called twitteruser. If the key-value is not set, the following will render nothing:

layouts/partials/twitter.html

1
2
3
4
5
{{ with .Site.Params.twitteruser }}<span class="twitter">
<a href="https://twitter.com/{{ . }}" rel="author">
<img src="/images/twitter.png" width="48" height="48" title="Twitter: {{ . }}"
 alt="Twitter"></a>
</span>{{ end }}