函数
- 1: 函数快速参考
- 2: .AddDate
- 3: .Format
- 4: .Get
- 5: .GetPage
- 6: .HasMenuCurrent
- 7: .IsMenuCurrent
- 8: .Param
- 9: .Render
- 10: .RenderString
- 11: .Scratch
- 12: .Store
- 13: .Unix
- 14: absLangURL
- 15: absURL
- 16: after
- 17: anchorize
- 18: append
- 19: apply
- 20: base64
- 21: chomp
- 22: complement
- 23: cond
- 24: countrunes
- 25: countwords
- 26: crypto.FNV32a
- 27: default
- 28: delimit
- 29: dict
- 30: duration
- 31: echoParam
- 32: emojify
- 33: eq
- 34: errorf 和 warnf
- 35: fileExists
- 36: findRE
- 37: findRESubmatch
- 38: first
- 39: float
- 40: ge
- 41: getenv
- 42: group
- 43: gt
- 44: highlight
- 45: hmac
- 46: htmlEscape
- 47: htmlUnescape
- 48: hugo
- 49: humanize
- 50: i18n
- 51: index
- 52: Image Filters
- 53: in
- 54: int
- 55: intersect
- 56: isset
- 57: jsonify
- 58: lang
- 59: lang.Merge
- 60: last
- 61: le
- 62: len
- 63: lower
- 64: lt
- 65: markdownify
- 66: Math
- 67: md5
- 68: merge
- 69: ne
- 70: now
- 71: os.Stat
- 72: partialCached
- 73: path.Base
- 74: path.BaseName
- 75: path.Clean
- 76: path.Dir
- 77: path.Ext
- 78: path.Join
- 79: path.Split
- 80: plainify
- 81: pluralize
- 82: print
- 83: printf
- 84: println
- 85: querify
- 86: range
- 87: readDir
- 88: readFile
- 89: ref
- 90: reflect.IsMap
- 91: reflect.IsSlice
- 92: relLangURL
- 93: relref
- 94: relURL
- 95: replace
- 96: replaceRE
- 97: safeCSS
- 98: safeHTML
- 99: safeHTMLAttr
- 100: safeJS
- 101: safeURL
- 102: seq
- 103: sha
- 104: shuffle
- 105: singularize
- 106: site
- 107: slice
- 108: slicestr
- 109: sort
- 110: split
- 111: string
- 112: strings.Contains
- 113: strings.ContainsAny
- 114: strings.Count
- 115: strings.FirstUpper
- 116: strings.HasPrefix
- 117: strings.HasSuffix
- 118: strings.Repeat
- 119: strings.RuneCount
- 120: strings.TrimLeft
- 121: strings.TrimPrefix
- 122: strings.TrimRight
- 123: strings.TrimSuffix
- 124: substr
- 125: symdiff
- 126: templates.Exists
- 127: time
- 128: time.Format
- 129: time.ParseDuration
- 130: title
- 131: transform.Unmarshal
- 132: trim
- 133: truncate
- 134: union
- 135: uniq
- 136: upper
- 137: urlize
- 138: urlquery
- 139: urls.Parse
- 140: where
- 141: with
1 - 函数快速参考
将以下英文翻译为中文:
Functions Quick Reference
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团队的解释。
|
|
另请参阅
3 - .Format
将以下英文翻译为中文:
.Format
https://gohugo.io/functions/format/
根据 Go 的布局字符串格式化内置的 Hugo 日期 —— .Date
, .PublishDate
和 .Lastmod
。
语法
.Format FORMAT
.Format
将格式化在前置元数据中定义的日期值,并可用作以下页面变量的属性:
.PublishDate
.Date
.Lastmod
假设内容文件前置元数据中有一个键值对 date: 2017-03-03
,可以通过 .Format
,后跟期望输出的布局字符串来将日期处理后再构建:
|
|
要格式化您前置元数据中定义的任何日期字符串表示形式,请参见 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函数将月份的日期渲染为序数:
|
|
这将输出:
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
返回一个空字符串而不是中断构建。这使您可以将 .Get
与 if
、with
、default
或 cond
链接在一起来检查参数是否存在。例如:
|
|
另请参阅
5 - .GetPage
将以下英文翻译为中文:
.GetPage
https://gohugo.io/functions/getpage/
获取给定 path
的 Page
。
语法
.GetPage PATH
.GetPage
返回给定 path
的页面。Site
和 Page
都实现了该方法。如果给定相对路径(即没有前导 /
的路径),Page
变量会尝试查找相对于当前页面的页面。
注意: 在 Hugo 0.45 中我们重新设计和简化了 .GetPage
API。在此之前,除了路径,您还需要提供一个 Kind
属性,例如 {{ .Site.GetPage "section" "blog" }}
。这仍然可以工作,但是现在是多余的(superfluous)。
|
|
当找不到页面时,此方法将返回 nil
,因此如果找不到blog章节,则上面的示例不会打印任何内容。
要在blog章节中查找一个常规页面:
|
|
由于 Page
还提供了一个 .GetPage
方法,因此上述示例与以下示例相同:
|
|
.GetPage
和多语言站点
前面的示例使用了完整的内容文件名来查找帖子。根据您的内容组织方式(文件名中是否有语言代码,例如 my-post.en.md
),您可能希望在没有扩展名的情况下进行查找。这将为您获取当前语言版本的页面:
|
|
.GetPage
示例
此代码片段(以局部模板的形式)允许您执行以下操作:
- 获取
tags
分类法的索引对象。 - 将该对象分配给变量
$t
。 - 按受欢迎程度排序与分类法相关联的条目。
- 获取分类法中最受欢迎的两个条目(即分配给内容的两个最受欢迎的标签)。
grab-top-two-tags.html
|
|
.GetPage
在页面bundle中
如果通过 .GetPage
检索到的页面是Leaf Bundle,并且您需要获取其中的嵌套page资源,则需要使用 .Resources
中的方法,如Page Resources中所述。
有关示例,请参见Headless Bundle文档。
另请参阅
6 - .HasMenuCurrent
将以下英文翻译为中文:
.HasMenuCurrent
https://gohugo.io/functions/hasmenucurrent/
语法
PAGE.HasMenuCurrent MENU MENUENTRY
.HasMenuCurrent
是 Page
对象中的一个方法,返回一个布尔值。如果 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
.IsMenuCurrent
是 Page
对象的一个方法,返回一个 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
|
|
.Param
方法返回与给定KEY
关联的值,无论该值是否为真值或假值。如果需要忽略假值,请改用此构造:
layouts/_default/single.html
|
|
另请参阅
9 - .Render
将以下英文翻译为中文:
.Render
https://gohugo.io/functions/render/
应用视图来渲染内容。
语法
.Render LAYOUT
该视图是一种替代布局,应该是一个文件名,指向 内容视图 文档中指定位置之一的模板。
此函数仅适用于 列表上下文 中的单个内容。
例如,下面的示例可以使用位于 /layouts/_default/summary.html
中的内容视图来渲染一篇内容:
|
|
另请参阅
10 - .RenderString
将以下英文翻译为中文:
.RenderString
https://gohugo.io/functions/renderstring/
将标记渲染为 HTML。
语法
.RenderString MARKUP
.RenderString
是 Page
上的方法,它使用为该页面定义的内容渲染器(如果选项中未设置)将一些标记渲染为 HTML。
该方法带有一个可选的 map 参数,其中包含以下选项:
display (“inline”)
inline
orblock
. Ifinline
(default), surrounding<p></p>
on short snippets will be trimmed.inline
或block
。如果是inline
(默认值),则会在简码片段周围修剪<p></p>
。markup (defaults to the Page’s markup)
请参见内容格式列表中的标识符。
以下是一些示例:
|
|
自 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 或 简码上下文中。
|
|
本地的 newScratch
使用 newScratch
函数,可以将 Scratch 实例分配给任何变量。 在这种情况下,不需要Page 或 简码上下文,而 Scratch 的作用域仅为本地。以下方法可以从已分配 Scratch 实例的变量中使用:
|
|
方法
Scratch 具有以下方法:
请注意,以下示例假设已在 $scratch
中存储了 本地 Scratch 实例。
.Set
设置给定键的值。
|
|
.Get
获取给定键的值。
|
|
.Add
将给定值添加到给定键的现有值中。
对于单个值,Add
接受支持 Go 的 +
运算符的值。如果某个键的第一个 Add
是一个数组或切片,则后续添加的内容将追加到该列表中。
|
|
.SetInMap
Takes a key
, mapKey
and value
and adds a map of mapKey
and value
to the given key
.
接收一个 key
、 mapKey
和 value
,并将 mapKey
和 value
的映射添加到给定的 key
中。
|
|
.DeleteInMap
Takes a key
and mapKey
and removes the map of mapKey
from the given key
.
接收一个 key
和 mapKey
,并从给定的 key
中删除 mapKey
的映射。
|
|
.GetSortedMapValues
Return an array of values from key
sorted by mapKey
.
按 mapKey
排序,返回 key
中的值数组。
|
|
.Delete
Remove the given key.
删除给定的键。
|
|
.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.
|
|
.Get
Gets the value of a given key.
|
|
.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.
|
|
.SetInMap
Takes a key
, mapKey
and value
and adds a map of mapKey
and value
to the given key
.
|
|
.DeleteInMap
Takes a key
and mapKey
and removes the map of mapKey
from the given key
.
|
|
.GetSortedMapValues
Returns an array of values from key
sorted by mapKey
.
|
|
.Delete
Removes the given key.
|
|
另请参阅
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.
|
|
另请参阅
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/
|
|
With baseURL = https://example.org/docs/
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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:
|
|
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:
- The top row is titled “Featured” and shows only the most recently published article (i.e. by
publishdate
in the content files’ front matter). - The second row is titled “Recent Articles” and shows only the 2nd- to 4th-most recently published articles.
layouts/section/articles.html
|
|
另请参阅
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.
|
|
另请参阅
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:
|
|
The same example appending a slice to a slice:
|
|
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.
- The first parameter is the sequence to operate on.
- The second parameter is the name of the function as a string, which must be the name of a valid Hugo function.
- 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:
|
|
Which will result in the following:
"derek-perkins", "joe-bergevin", "tanner-linsley"
This is roughly equivalent to using the following with range:
|
|
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
|
|
layouts/partials/post-tag-link.html
|
|
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:
|
|
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
|
|
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.
|
|
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
).
|
|
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
:
|
|
Make your code simpler to understand by using a chained pipeline:
|
|
You can also use the complement
function with page collections. Let’s say your site has five content types:
|
|
To list everything except blog articles (blog
) and frequently asked questions (faqs
):
|
|
Although the example above demonstrates the complement
function, you could use the where
function as well:
|
|
In this example we use the complement
function to remove stop words from a sentence:
|
|
另请参阅
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:
|
|
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.
|
|
另请参阅
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.
|
|
另请参阅
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
|
|
default
可以以多种方式编写:
|
|
上述两个 default
函数调用都返回Roboto
。
但是,default
值不需要像上面的例子一样被硬编码。default
值可以是变量或直接使用点符号从前置元数据中提取:
|
|
它将返回:
|
|
然后使用点符号:
|
|
它将返回:
|
|
以下内容具有等效的返回值,但default
更为简洁。这演示了default
的实用性:
使用if
:
|
|
使用with
:
|
|
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:
|
|
Delimit a map:
The delimit
function sorts maps by key, returning the values.
|
|
另请参阅
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.:
|
|
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
|
|
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
|
|
另请参阅
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:
Duration | Valid time units |
---|---|
hours | hour , h |
minutes | minute , m |
seconds | second , s |
milliseconds | millisecond , ms |
microseconds | microsecond , us , µs |
nanoseconds | nanosecond , 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.
|
|
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.
|
|
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:
|
|
The function returns these values:
|
|
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
:
|
|
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:
|
|
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
|
|
Practical example
This markdown:
|
|
Produces this HTML:
|
|
To match the anchor elements, capturing the link destination and text:
|
|
Viewed as JSON, the data structure of $matches
in the code above is:
|
|
To render the href
attributes:
|
|
Result:
|
|
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:
number of elements
array
orslice of maps or structs
layout/_default/section.html
|
|
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
|
|
另请参阅
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:
|
|
With a binary (base 2) input:
|
|
With an octal (base 8) input (use either notation):
|
|
With a hexadecimal (base 16) input:
|
|
另请参阅
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:
|
|
You can pass values when building your site:
|
|
And then retrieve the values within a template:
|
|
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
|
|
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 iflineNos
isfalse
.anchorLineNos
Boolean. Default is
false
. Render each line number as an HTML anchor element, and set theid
attribute of the surrounding<span>
to the line number. Irrelevant iflineNos
isfalse
.lineAnchors
String. Default is
""
. When rendering a line number as an HTML anchor element, prepend this value to theid
attribute of the surrounding<span>
. This provides uniqueid
attributes when a page contains two or more code blocks. Irrelevant iflineNos
oranchorLineNos
isfalse
.lineNoStart
Integer. Default is
1
. The number to display at the beginning of the first line. Irrelevant iflineNos
isfalse
.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 to2-4 7
. This option is independent of thelineNoStart
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 tofalse
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 ifnoClasses
isfalse
.guessSyntax
Boolean. Default is
false
. If theLANG
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
andlineNumbersInTable=false
lineNos=table
equivalent to
lineNos=true
andlineNumbersInTable=true
Examples
|
|
另请参阅
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
.
|
|
另请参阅
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 "
.
|
|
另请参阅
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.
|
|
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 taghugo.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 environmenthugo.Deps
See hugo.Deps
hugo.Deps
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:
|
|
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.
|
|
另请参阅
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.
|
|
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
:
|
|
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.:
|
|
The function takes multiple indices as arguments, and this can be used to get nested values, e.g.:
|
|
You may write multiple indices as a slice:
|
|
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:
- The node path
- A string corresponding to the desired data; e.g.—
|
|
The variable for .Params.location
is a string and can therefore replace oslo
in the example above:
|
|
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 (.
):
|
|
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:
|
|
A shorter version of the above, if you only need to apply the filter once:
|
|
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.
|
|
You can load a custom font if needed. Load the font as a Hugo Resource
and set it as an option:
|
|
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:
|
|
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.
|
|
另请参阅
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.
|
|
另请参阅
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:
|
|
With a binary (base 2) input:
|
|
With an octal (base 8) input (use either notation):
|
|
With a hexadecimal (base 16) input:
|
|
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
|
|
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.
|
|
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.
|
|
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
|
|
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
|
|
lang.FormatNumber
FormatNumber formats number with the given precision for the current language.
语法
lang.FormatNumber PRECISION, NUMBER
Examples
|
|
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
|
|
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
|
|
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:
|
|
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:
|
|
另请参阅
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:
|
|
With a slice:
|
|
With a map:
|
|
With a collection:
|
|
You may also determine the number of pages in a collection with:
|
|
另请参阅
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:
|
|
另请参阅
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.
Function | Description | Example |
---|---|---|
add | Adds 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 | |
sub | Subtracts 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 | |
mul | Multiplies 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 | |
div | Divides 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 | |
mod | Modulus of two integers. | {{ mod 15 3 }} → 0 |
modBool | Boolean of modulus of two integers. Evaluates to true if result equals 0. | {{ modBool 15 3 }} → true |
math.Ceil | Returns the least integer value greater than or equal to the given number. | {{ math.Ceil 2.1 }} → 3 |
math.Floor | Returns the greatest integer value less than or equal to the given number. | {{ math.Floor 1.9 }} → 1 |
math.Log | Returns the natural logarithm of the given number. | {{ math.Log 42 }} → 3.737 |
math.Max | Returns the greater of two or more numbers. | {{ math.Max 12 3 2 }} → 12 |
math.Min | Returns the smaller of two or more numbers. | {{ math.Min 12 3 2 }} → 2 |
math.Pow | Returns the first number raised to the power of the second number. | {{ math.Pow 2 3 }} → 8 |
math.Round | Returns the nearest integer, rounding half away from zero. | {{ math.Round 1.5 }} → 2 |
math.Sqrt | Returns 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:
|
|
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:
|
|
Example 1
|
|
Example 2
|
|
Example 3
|
|
Example 4
|
|
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:
|
|
would produce the following:
|
|
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.
|
|
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:
|
|
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
|
|
If you need to pass additional parameters to create unique variants, you can pass as many variant parameters as you need:
|
|
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.
|
|
另请参阅
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.
|
|
另请参阅
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.
|
|
On a Windows system, if .File.Path
is foo\bar.md
, then:
|
|
另请参阅
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.
|
|
另请参阅
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.
|
|
另请参阅
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.
|
|
另请参阅
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.
|
|
另请参阅
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
将以下英文翻译为中文:
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.
|
|
另请参阅
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.
|
|
另请参阅
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:
|
|
另请参阅
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.
|
|
Both of these examples render the following HTML:
|
|
另请参阅
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:
|
|
This template code:
|
|
Produces:
|
|
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:
|
|
This template code:
|
|
Produces:
|
|
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.
|
|
To return the absolute permalink to another language version of a page:
|
|
To return the absolute permalink to another Output Format of a page:
|
|
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.
|
|
另请参阅
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.
|
|
另请参阅
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/
|
|
With baseURL = https://example.org/docs/
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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.
|
|
The permalink returned is relative to the protocol+host portion of the baseURL specified in the site configuration. For example:
Code | baseURL | Permalink |
---|---|---|
{{ 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:
|
|
To return the relative permalink to another Output Format of a page:
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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/
|
|
With baseURL = https://example.org/docs/
|
|
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:
|
|
To limit the number of replacements to one:
|
|
You can use $1
, $2
, etc. within the replacement string to insert the groups captured within the regular expression:
|
|
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:
- The CSS3 stylesheet production, such as
p { color: purple }
. - The CSS3 rule production, such as
a[href=~"https:"].foo#bar
. - CSS3 declaration productions, such as
color: red; margin: 2px
. - 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:
|
|
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:
|
|
另请参阅
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:
|
|
Will produce:
|
|
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:
|
|
另请参阅
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
|
|
This partial would produce the following HTML output:
|
|
The odd output can be remedied by adding | safeURL
to our .URL
page variable:
layouts/partials/correct-url-sidebar-menu.html
|
|
With the .URL
page variable piped through safeURL
, we get the desired output:
|
|
另请参阅
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:
|
|
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.
|
|
sha256
hashes the given input and returns its SHA256 checksum.
|
|
另请参阅
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
|
|
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
|
|
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
|
|
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
|
|
These produce:
|
|
Descending order
Sort map objects in descending order:
layouts/_default/single.html
|
|
This produces:
|
|
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
|
|
另请参阅
110 - split
将以下英文翻译为中文:
split
https://gohugo.io/functions/split/
Returns a slice of strings by splitting STRING by DELIM.
语法
split STRING DELIM
Examples:
|
|
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:
|
|
With a binary (base 2) input:
|
|
With an octal (base 8) input (use either notation):
|
|
With a hexadecimal (base 16) input:
|
|
另请参阅
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
.
Example | Result |
---|---|
`{{ “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.
|
|
另请参阅
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.
|
|
另请参阅
125 - symdiff
将以下英文翻译为中文:
symdiff
https://gohugo.io/functions/symdiff/
collections.SymDiff
(alias symdiff
) returns the symmetric difference of two collections.
语法
COLLECTION | symdiff COLLECTION
Example:
|
|
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.
|
|
另请参阅
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:
|
|
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.
|
|
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
|
|
另请参阅
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.
|
|
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:
|
|
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:
|
|
In both the above examples, you get a map you can work with:
|
|
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:
|
|
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 }}
:
|
|
The following example lists the items of an RSS feed:
|
|
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:
|
|
Instead, the following example tells trim
to remove extra new lines from the content contained in the shortcode .Inner
variable:
|
|
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:
|
|
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).
|
|
OR filter in where query
This is also very useful to use as OR
filters when combined with where:
|
|
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:
|
|
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
|
|
The preceding partial would then output to the rendered page as follows:
|
|
另请参阅
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:
|
|
Is rendered to:
|
|
另请参阅
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.
|
|
另请参阅
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.
|
|
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"
}
```
|
|
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 =
.
|
|
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 valuein
true
if a given field value is included in a matching value; a matching value must be an array or a slicenot in
true
if a given field value isn’t included in a matching value; a matching value must be an array or a sliceintersect
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 theintersect
function.
Use where
with Booleans
When using booleans you should not put quotation marks.
|
|
Use where
with intersect
|
|
You can also put the returned value of the where
clauses into a variable:
where-intersect-variables.html
|
|
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
|
|
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:
|
|
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.
|
|
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"
.
|
|
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
|
|