HUGO
Menu
GitHub 87548 stars Mastodon

函数

Hugo 函数的快速参考指南,按命名空间分组。别名(如有)显示在函数名称右侧的括号中。

cast

Hugo 使用这些函数将值从一种数据类型转换为另一种数据类型。

Hugo cast.ToFloat
Hugo 将值转换为十进制浮点数(以 10 为基数)。
Hugo cast.ToInt
Hugo 将值转换为十进制整数(以 10 为基数)。
Hugo cast.ToString
Hugo 将值转换为字符串。

collections

Hugo 使用这些函数来操作和查询映射、切片和字符串。

Hugo collections.After
Hugo Returns a slice containing the elements after the first N elements of the given slice.
Hugo collections.Append
Hugo Returns a slice by adding one or more elements, or an entire second slice, to the end of the given slice.
Hugo collections.Apply
Hugo Returns a slice by transforming each element of the given slice using a specific function and parameters.
Hugo collections.Complement
Hugo Returns a slice by identifying elements in the last given slice that do not appear in any of the preceding slices.
Hugo collections.D
Hugo Returns a sorted slice of unique random integers based on a given seed, count, and maximum value.
Hugo collections.Delimit
Hugo Returns a string by joining the values of the given slice or map with a delimiter.
Hugo collections.Dictionary
Hugo Returns a map created from the given key-value pairs.
Hugo collections.First
Hugo Returns the first N elements of the given slice or string.
Hugo collections.Group
Hugo Returns a map by grouping the given page collection (slice) by a specific key.
Hugo collections.In
Hugo Reports whether a value exists within the given slice or string.
Hugo collections.Index
Hugo Returns an element or value from the given slice or map at the specified key(s).
Hugo collections.Intersect
Hugo Returns a slice containing the common elements found in two given slices, in the same order as the first slice.
Hugo collections.IsSet
Hugo Reports whether a specific key or index exists in the given map or slice.
Hugo collections.KeyVals
Hugo Returns a KeyVals struct by pairing a given key and values.
Hugo collections.Last
Hugo Returns the last N elements of the given slice or string.
Hugo collections.Merge
Hugo Returns a map by combining two or more given maps.
Hugo collections.NewScratch
Hugo Returns a locally scoped "scratch pad" to store and manipulate data.
Hugo collections.Querify
Hugo Returns a URL query string from the given map, slice, or sequence of key-value pairs.
Hugo collections.Reverse
Hugo Returns a slice by reversing the order of elements in the given slice.
Hugo collections.Seq
Hugo Returns a slice of integers starting from 1 or a given value, incrementing by 1 or a given value, and ending at a given value.
Hugo collections.Shuffle
Hugo Returns a slice by randomizing the element order of the given slice.
Hugo collections.Slice
Hugo Returns a slice created from the given values.
Hugo collections.Sort
Returns a sorted map or slice by reordering the given collection by a key and order.
Hugo collections.SymDiff
Hugo Returns a slice containing the symmetric difference of two given slices.
Hugo collections.Union
Hugo Returns a slice containing the unique elements from two given slices.
Hugo collections.Uniq
Hugo Returns a slice by removing duplicate elements from the given slice.
Hugo collections.Where
Hugo Returns a slice by filtering the given slice based on a key, operator, and value.

compare

Hugo 使用这些函数来比较两个或多个值。

Hugo compare.Conditional
Returns one of two arguments depending on the value of the control argument.
Hugo compare.Default
Returns the second argument if set, else the first argument.
Hugo compare.Eq
Returns the boolean truth of arg1 == arg2 || arg1 == arg3.
Hugo compare.Ge
Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3.
Hugo compare.Gt
Returns the boolean truth of arg1 > arg2 && arg1 > arg3.
Hugo compare.Le
Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3.
Hugo compare.Lt
Returns the boolean truth of arg1 < arg2 && arg1 < arg3.
Hugo compare.Ne
Returns the boolean truth of arg1 != arg2 && arg1 != arg3.

crypto

Hugo 使用这些函数创建加密哈希。

Hugo crypto.FNV32a
Returns the 32-bit FNV (Fowler-Noll-Vo) non-cryptographic hash of the given string.
Hugo crypto.HMAC
Returns a cryptographic hash that uses a key to sign a message.
Hugo crypto.MD5
Hashes the given input and returns its MD5 checksum encoded to a hexadecimal string.
Hugo crypto.SHA1
Hashes the given input and returns its SHA1 checksum encoded to a hexadecimal string.
Hugo crypto.SHA256
Hashes the given input and returns its SHA256 checksum encoded to a hexadecimal string.

css

Hugo 使用这些函数处理 CSS 和 Sass 文件。

Hugo css.PostCSS
Processes the given resource with PostCSS using any PostCSS plugin in Hugo.
Hugo css.Quoted
Returns the given string, setting its data type to indicate that it must be quoted when used in CSS.
Hugo css.Sass
Transpiles Sass to CSS.
Hugo css.TailwindCSS
Processes the given resource with the Tailwind CSS CLI.
Hugo css.Unquoted
Returns the given string, setting its data type to indicate that it must not be quoted when used in CSS.

data

Hugo 使用这些函数读取本地或远程数据文件。

debug

Hugo 使用这些函数来调试模板。

debug.VisualizeSpaces
Returns the given string with spaces replaced by a visible string.
Hugo debug.Dump
Returns an object dump as a string.
Hugo debug.Timer
Creates a named timer that reports elapsed time to the console.

diagrams

Hugo 使用这些函数来渲染图表。

diagrams.Goat
Returns an SVGDiagram object created from the given GoAT markup and options.

encoding

Hugo 使用这些函数来编码和解码数据。

Hugo encoding.Base64Decode
Hugo Returns the base64 decoding of the given content.
Hugo encoding.Base64Encode
Hugo Returns the base64 decoding of the given content.
Hugo encoding.Jsonify
Hugo Encodes the given object to JSON.

fmt

Hugo 使用这些函数在模板中打印字符串或向终端打印消息。

Hugo fmt.Errorf
Log an ERROR from a template.
Hugo fmt.Erroridf
Log a suppressible ERROR from a template.
Hugo fmt.Print
Prints the default representation of the given arguments using the standard fmt.Print function.
Hugo fmt.Printf
Formats a string using the standard fmt.Sprintf function.
Hugo fmt.Println
Hugo Prints the default representation of the given argument using the standard fmt.Print function and enforces a line break.
Hugo fmt.Warnf
Log a WARNING from a template.
Hugo fmt.Warnidf
Hugo Log a suppressible WARNING from a template.

global

Hugo 使用这些全局函数来访问页面和站点数据。

Hugo page
Provides global access to a Page object.
Hugo site
Hugo Provides global access to the current Site object.

go template

这些是由 Go 的 text/template 包提供的函数、运算符和语句。

and
Returns the first falsy argument. If all arguments are truthy, returns the last argument.
block
Defines a template and executes it in place.
break
Used with the range statement, stops the innermost iteration and bypasses all remaining iterations.
continue
Used with the range statement, stops the innermost iteration and continues to the next iteration.
define
Defines a template.
else
Begins an alternate block for if, with, and range statements.
end
Terminates if, with, range, block, and define statements.
if
Executes the block if the expression is truthy.
len
Returns the length of a string, slice, map, or collection.
not
Returns the boolean negation of its single argument.
or
Returns the first truthy argument. If all arguments are falsy, returns the last argument.
range
Iterates over a non-empty collection, binds context (the dot) to successive elements, and executes the block.
return
Used within partial templates, terminates template execution and returns the given value, if any.
template
Executes the given template, optionally passing context.
try
Returns a TryValue object after evaluating the given expression.
urlquery
Returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.
with
Binds context (the dot) to the expression and executes the block if expression is truthy.

hash

Hugo 使用这些函数创建非加密哈希。

hash.FNV32a
Returns the 32-bit FNV (Fowler-Noll-Vo) non-cryptographic hash of the given string.
hash.XxHash
Returns the 64-bit xxHash non-cryptographic hash of the given string.

hugo

Hugo 使用这些函数访问 Hugo 应用程序和当前环境的信息。

hugo.BuildDate
Returns the compile date of the Hugo binary.
hugo.CommitHash
Returns the Git commit hash of the Hugo binary.
hugo.Deps
Returns a slice of project dependencies, either Hugo Modules or local theme components.
hugo.Environment
Returns the current running environment.
hugo.Generator
Renders an HTML meta element identifying the software that generated the site.
hugo.GoVersion
Returns the Go version used to compile the Hugo binary
hugo.IsDevelopment
Reports whether the current running environment is "development".
hugo.IsExtended
Reports whether the Hugo binary is either the extended or extended/deploy edition.
hugo.IsMultihost
Reports whether each configured language has a unique base URL.
hugo.IsMultilingual
Reports whether there are two or more configured languages.
hugo.IsProduction
Reports whether the current running environment is "production".
hugo.IsServer
Reports whether the built-in development server is running.
hugo.Store
Returns a globally scoped "scratch pad" to store and manipulate data.
hugo.Version
Returns the current version of the Hugo binary.
hugo.WorkingDir
Returns the project working directory.

images

Hugo 使用这些函数创建图像滤镜、将图像滤镜应用于图像以及获取图像信息。

images.AutoOrient
Returns an image filter that rotates and flips an image as needed per its Exif orientation tag.
images.Brightness
Returns an image filter that changes the brightness of an image.
images.ColorBalance
Returns an image filter that changes the color balance of an image.
images.Colorize
Returns an image filter that produces a colorized version of an image.
images.Config
Returns an image.Config structure from the image at the specified path, relative to the working directory.
images.Contrast
Returns an image filter that changes the contrast of an image.
images.Dither
Returns an image filter that dithers an image.
images.Filter
Applies one or more image filters to the given image resource.
images.Gamma
Returns an image filter that performs gamma correction on an image.
images.GaussianBlur
Returns an image filter that applies a gaussian blur to an image.
images.Grayscale
Returns an image filter that produces a grayscale version of an image.
images.Hue
Returns an image filter that rotates the hue of an image.
images.Invert
Returns an image filter that negates the colors of an image.
images.Mask
Returns an image filter that applies a mask to the source image.
images.Opacity
Returns an image filter that changes the opacity of an image.
images.Overlay
Returns an image filter that overlays the source image at the given coordinates, relative to the upper left corner.
images.Padding
Returns an image filter that resizes the image canvas without resizing the image.
images.Pixelate
Returns an image filter that applies a pixelation effect to an image.
images.Process
Returns an image filter that processes an image according to the given processing specification.
images.QR
Encodes the given text into a QR code using the specified options, returning an image resource.
images.Saturation
Returns an image filter that changes the saturation of an image.
images.Sepia
Returns an image filter that produces a sepia-toned version of an image.
images.Sigmoid
Returns an image filter that changes the contrast of an image using a sigmoidal function.
images.Text
Returns an image filter that adds text to an image.
images.UnsharpMask
Returns an image filter that sharpens an image.

inflect

Hugo 这些函数提供词形变化功能,如英语名词的单复数转换。

inflect.Humanize
Returns the humanized version of the input with the first letter capitalized.
inflect.Pluralize
Pluralizes the given word according to a set of common English pluralization rules.
inflect.Singularize
Singularizes the given word according to a set of common English singularization rules.

js

Hugo 使用这些函数处理 JavaScript 和 TypeScript 文件。

js.Babel
Compile the given JavaScript resource with Babel.
js.Batch
Build JavaScript bundle groups with global code splitting and flexible hooks/runners setup.
js.Build
Bundle, transpile, tree shake, and minify JavaScript resources.

lang

Hugo 使用这些函数使您的网站适应语言和区域需求。

lang.FormatAccounting
Returns a currency representation of a number for the given currency and precision for the current language and region in accounting notation.
lang.FormatCurrency
Returns a currency representation of a number for the given currency and precision for the current language and region.
lang.FormatNumber
Returns a numeric representation of a number with the given precision for the current language and region.
lang.FormatNumberCustom
Returns a numeric representation of a number with the given precision using negative, decimal, and grouping options.
lang.FormatPercent
Returns a percentage representation of a number with the given precision for the current language and region.
lang.Merge
Merge missing translations from other languages.
lang.Translate
Translates a string using the translation tables in the i18n directory.

math

Hugo 使用这些函数执行数学运算。

math.Abs
Returns the absolute value of the given number.
math.Acos
Returns the arccosine, in radians, of the given number.
math.Add
Adds two or more numbers.
math.Asin
Returns the arcsine, in radians, of the given number.
math.Atan
Returns the arctangent, in radians, of the given number.
math.Atan2
Returns the arctangent, in radians, of the given number pair, determining the correct quadrant from their signs.
math.Ceil
Returns the least integer value greater than or equal to the given number.
math.Cos
Returns the cosine of the given radian number.
math.Counter
Increments and returns a global counter.
math.Div
Divides the first number by one or more numbers.
math.Floor
Returns the greatest integer value less than or equal to the given number.
math.Log
Returns the natural logarithm of the given number.
math.Max
Returns the greater of all numbers. Accepts scalars, slices, or both.
math.MaxInt64
Returns the maximum value for a signed 64-bit integer.
math.Min
Returns the smaller of all numbers. Accepts scalars, slices, or both.
math.Mod
Returns the modulus of two integers.
math.ModBool
Reports whether the modulus of two integers equals 0.
math.Mul
Multiplies two or more numbers.
math.Pi
Returns the mathematical constant pi.
math.Pow
Returns the first number raised to the power of the second number.
math.Product
Returns the product of all numbers. Accepts scalars, slices, or both.
math.Rand
Returns a pseudo-random number in the half-open interval [0.0, 1.0).
math.Round
Returns the nearest integer, rounding half away from zero.
math.Sin
Returns the sine of the given radian number.
math.Sqrt
Returns the square root of the given number.
math.Sub
Subtracts one or more numbers from the first number.
math.Sum
Returns the sum of all numbers. Accepts scalars, slices, or both.
math.Tan
Returns the tangent of the given radian number.
math.ToDegrees
ToDegrees converts radians into degrees.
math.ToRadians
ToRadians converts degrees into radians.

openapi3

Hugo 使用这些函数处理 OpenAPI 3 定义。

openapi3.Unmarshal
Unmarshals the given resource into an OpenAPI 3 Description.

os

Hugo 使用这些函数与操作系统交互。

os.FileExists
Reports whether the file or directory exists.
os.Getenv
Returns the value of an environment variable, or an empty string if the environment variable is not set.
os.ReadDir
Returns an array of FileInfo structures sorted by file name, one element for each directory entry.
os.ReadFile
Returns the contents of a file.
os.Stat
Returns a FileInfo structure describing a file or directory.

partials

Hugo 使用这些函数调用局部模板。

partials.Include
Executes the given template, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output.
partials.IncludeCached
Executes the given template and caches the result, optionally passing one or more variant keys. If the partial template contains a return statement, returns the given value, else returns the rendered output.

path

Hugo 使用这些函数处理文件路径。

path.Base
Replaces path separators with slashes (/) and returns the last element of the given path.
path.BaseName
Replaces path separators with slashes (/) and returns the last element of the given path, removing the extension if present.
path.Clean
Replaces path separators with slashes (/) and returns the shortest path name equivalent to the given path.
path.Dir
Replaces path separators with slashes (/) and returns all but the last element of the given path.
path.Ext
Replaces path separators with slashes (/) and returns the file name extension of the given path.
path.Join
Replaces path separators with slashes (/), joins the given path elements into a single path, and returns the shortest path name equivalent to the result.
path.Split
Replaces path separators with slashes (/) and splits the resulting path immediately following the final slash, separating it into a directory and file name component.

reflect

Hugo 使用这些函数确定值的数据类型。

reflect.IsImageResource
Reports whether the given value is a Resource object representing a processable image.
reflect.IsMap
Reports whether the given value is a map.
reflect.IsPage
Reports whether the given value is a Page object.
reflect.IsResource
Reports whether the given value is a Resource object.
reflect.IsSite
Reports whether the given value is a Site object.
reflect.IsSlice
Reports whether the given value is a slice.

resources

Hugo 使用这些函数处理资源。

resources.Babel
Compiles the given JavaScript resource with Babel.
resources.ByType
Returns a collection of global resources of the given media type, or nil if none found.
resources.Concat
Returns a concatenated slice of resources.
resources.Copy
Copies the given resource to the target path.
resources.ExecuteAsTemplate
Returns a resource created from a Go template, parsed and executed with the given context.
resources.Fingerprint
Cryptographically hashes the content of the given resource.
resources.FromString
Returns a resource created from a string.
resources.Get
Returns a global resource from the given path, or nil if none found.
resources.GetMatch
Returns the first global resource from paths matching the given glob pattern, or nil if none found.
resources.GetRemote
Returns a remote resource from the given URL, or nil if none found.
resources.Match
Returns a collection of global resources from paths matching the given glob pattern, or nil if none found.
resources.Minify
Minifies the given resource.
resources.PostCSS
Processes the given resource with PostCSS using any PostCSS plugin.
resources.PostProcess
Processes the given resource after the build.
resources.ToCSS
Transpiles Sass to CSS.

safe

Hugo 使用这些函数在 Go 的 html/template 包上下文中声明值为安全。

safe.CSS
Declares the given string as a safe CSS string.
safe.HTML
Declares the given string as a safeHTML string.
safe.HTMLAttr
Declares the given key-value pair as a safe HTML attribute.
safe.JS
Declares the given string as a safe JavaScript expression.
safe.JSStr
Declares the given string as a safe JavaScript string.
safe.URL
Declares the given string as a safe URL or URL substring.

strings

Hugo 使用这些函数处理字符串。

strings.Chomp
Returns the given string, removing all trailing newline characters and carriage returns.
strings.Contains
Reports whether the given string contains the given substring.
strings.ContainsAny
Reports whether the given string contains any character within the given set.
strings.ContainsNonSpace
Reports whether the given string contains any non-space characters as defined by Unicode.
strings.Count
Returns the number of non-overlapping instances of the given substring within the given string.
strings.CountRunes
Returns the number of runes in the given string excluding whitespace.
strings.CountWords
Returns the number of words in the given string.
strings.Diff
Returns an anchored diff of the two texts OLD and NEW in the unified diff format. If OLD and NEW are identical, returns an empty string.
strings.FindRE
Returns a slice of strings that match the regular expression.
strings.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.
strings.FirstUpper
Returns the given string, capitalizing the first character.
strings.HasPrefix
Reports whether the given string begins with the given prefix.
strings.HasSuffix
Reports whether the given string ends with the given suffix.
strings.Repeat
Returns a new string consisting of zero or more copies of another string.
strings.Replace
Returns a copy of INPUT, replacing all occurrences of OLD with NEW.
strings.ReplaceRE
Returns a copy of INPUT, replacing all occurrences of a regular expression with a replacement pattern.
strings.RuneCount
Returns the number of runes in the given string.
strings.SliceString
Returns a substring of the given string, beginning with the start position and ending before the end position.
strings.Split
Returns a slice of strings by splitting the given string by a delimiter.
strings.Substr
Returns a substring of the given string, beginning with the start position and ending after the given length.
strings.Title
Returns the given string, converting it to title case.
strings.ToLower
Returns the given string, converting all characters to lowercase.
strings.ToUpper
Returns the given string, converting all characters to uppercase.
strings.Trim
Returns the given string, removing leading and trailing characters specified in the cutset.
strings.TrimLeft
Returns the given string, removing leading characters specified in the cutset.
strings.TrimPrefix
Returns the given string, removing the prefix from the beginning of the string.
strings.TrimRight
Returns the given string, removing trailing characters specified in the cutset.
strings.TrimSpace
Returns the given string, removing leading and trailing whitespace as defined by Unicode.
strings.TrimSuffix
Returns the given string, removing the suffix from the end of the string.
strings.Truncate
Returns the given string, truncating it to a maximum length without cutting words or leaving unclosed HTML tags.

templates

Hugo 使用这些函数查询模板系统。

templates.Current
Returns information about the currently executing template.
templates.Defer
Defer execution of a template until after all sites and output formats have been rendered.
templates.Exists
Reports whether a template file exists under the given path relative to the layouts directory.
templates.Inner
Executes the content block enclosed by a partial call.

time

Hugo 使用这些函数处理时间值。

time.AsTime
Returns the given string representation of a date/time value as a time.Time value.
time.Duration
Returns a time.Duration value using the given time unit and number.
time.Format
Returns the given date/time as a formatted and localized string.
time.In
Returns the given date/time as represented in the specified IANA time zone.
time.Now
Returns the current local time.
time.ParseDuration
Returns a time.Duration value by parsing the given duration string.

transform

Hugo 使用这些函数将值从一种格式转换为另一种格式。

transform.CanHighlight
Reports whether the given code language is supported by the Chroma highlighter.
transform.Emojify
Runs a string through the Emoji emoticons processor.
transform.Highlight
Renders code with a syntax highlighter.
transform.HighlightCodeBlock
Highlights code received in context within a code block render hook.
transform.HTMLEscape
Returns the given string, escaping special characters by replacing them with HTML entities.
transform.HTMLToMarkdown
Converts HTML to Markdown.
transform.HTMLUnescape
Returns the given string, replacing each HTML entity with its corresponding character.
transform.Markdownify
Renders Markdown to HTML.
transform.Plainify
Returns a string with all HTML tags removed.
transform.PortableText
Converts Portable Text to Markdown.
transform.Remarshal
Marshals a string of serialized data, or a map, into a string of serialized data in the specified format.
transform.ToMath
Renders mathematical equations and expressions written in the LaTeX markup language.
transform.Unmarshal
Parses serialized data and returns a map or an array. Supports CSV, JSON, TOML, YAML, and XML.
transform.XMLEscape
Returns the given string, removing disallowed characters then escaping the result to its XML equivalent.

urls

Hugo 使用这些函数处理 URL。

urls.AbsLangURL
Returns an absolute URL with a language prefix, if any.
urls.AbsURL
Returns an absolute URL.
urls.Anchorize
Returns the given string, sanitized for usage in an HTML id attribute.
urls.JoinPath
Joins the provided elements into a URL string and cleans the result of any ./ or ../ elements. If the argument list is empty, JoinPath returns an empty string.
urls.Parse
Parses a URL into a URL structure.
urls.PathEscape
Returns the given string, replacing all percent-encoded sequences with the corresponding unescaped characters.
urls.PathUnescape
Returns the given string, applying percent-encoding to special characters and reserved delimiters so it can be safely used as a segment within a URL path.
urls.Ref
Returns the absolute URL of the page with the given path, language, and output format.
urls.RelLangURL
Returns a relative URL with a language prefix, if any.
urls.RelRef
Returns the relative URL of the page with the given path, language, and output format.
urls.RelURL
Returns a relative URL.
urls.URLize
Returns the given string, sanitized for usage in a URL.

Last updated: January 1, 0001
Improve this page