HUGO
News Docs Themes Community GitHub

Functions

A quick reference guide to Hugo’s functions, grouped by namespace. Aliases, if any, appear in parentheses to the right of the function name.

cast

Use these functions to cast a value from one data type to another.

cast.ToFloat (float)
Converts a value to a decimal floating-point number (base 10).
cast.ToInt (int)
Converts a value to a decimal integer (base 10).
cast.ToString (string)
Converts a value to a string.

collections

Use these functions to work with arrays, slices, maps, and page collections.

collections.After (after)
Slices an array to the items after the Nth item.
collections.Append (append)
Appends one or more elements to a slice and returns the resulting slice.
collections.Apply (apply)
Returns a new collection with each element transformed by the given function.
collections.Complement (complement)
Returns the elements of the last collection that are not in any of the others.
collections.Delimit (delimit)
Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.
collections.Dictionary (dict)
Returns a map composed of the given key-value pairs.
collections.First (first)
Returns the given collection, limited to the first N elements.
collections.Group (group)
Groups the given page collection by the given key.
collections.In (in)
Reports whether the given value is a member of the given set.
collections.Index (index)
Returns the object, element, or value associated with the given key or keys.
collections.Intersect (intersect)
Returns the common elements of two arrays or slices, in the same order as the first array.
collections.IsSet (isset)
Reports whether the key exists within the collection.
collections.KeyVals (keyVals)
Returns a KeyVals struct.
collections.Last (last)
Returns the given collection, limited to the last N elements.
collections.Merge (merge)
Returns the result of merging two or more maps.
collections.NewScratch (newScratch)
Returns a locally scoped "scratch pad" to store and manipulate data.
collections.Querify (querify)
Returns a URL query string composed of the given key-value pairs, encoded and sorted by key.
collections.Reverse
Reverses the order of a collection.
collections.Seq (seq)
Returns a slice of integers.
collections.Shuffle (shuffle)
Returns a random permutation of a given array or slice.
collections.Slice (slice)
Returns a slice composed of the given values.
collections.Sort (sort)
Sorts slices, maps, and page collections.
collections.SymDiff (symdiff)
Returns the symmetric difference of two collections.
collections.Union (union)
Given two arrays or slices, returns a new array that contains the elements that belong to either or both arrays/slices.
collections.Uniq (uniq)
Returns the given collection, removing duplicate elements.
collections.Where (where)
Returns the given collection, removing elements that do not satisfy the comparison condition.

compare

Use these functions to compare two or more values.

compare.Conditional (cond)
Returns one of two arguments depending on the value of the control argument.
compare.Default (default)
Returns the second argument if set, else the first argument.
compare.Eq (eq)
Returns the boolean truth of arg1 == arg2 || arg1 == arg3.
compare.Ge (ge)
Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3.
compare.Gt (gt)
Returns the boolean truth of arg1 > arg2 && arg1 > arg3.
compare.Le (le)
Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3.
compare.Lt (lt)
Returns the boolean truth of arg1 < arg2 && arg1 < arg3.
compare.Ne (ne)
Returns the boolean truth of arg1 != arg2 && arg1 != arg3.

crypto

Use these functions to create cryptographic hashes.

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

css

Use these functions to work with CSS and Sass files.

css.PostCSS (postCSS)
Processes the given resource with PostCSS using any PostCSS plugin.
css.Sass (toCSS)
Transpiles Sass to CSS.
css.TailwindCSS
Processes the given resource with the Tailwind CSS CLI.

data

Use these functions to read local or remote data files.

data.GetCSV (getCSV)
Returns an array of arrays from a local or remote CSV file, or an error if the file does not exist.
data.GetJSON (getJSON)
Returns a JSON object from a local or remote JSON file, or an error if the file does not exist.

debug

Use these functions to debug your templates.

debug.Dump
Returns an object dump as a string.
debug.Timer
Creates a named timer that reports elapsed time to the console.

diagrams

Use these functions to render diagrams.

diagrams.Goat
Converts ASCII art to an SVG diagram, returning a GoAT diagram object.

encoding

Use these functions to encode and decode data.

encoding.Base64Decode (base64Decode)
Returns the base64 decoding of the given content.
encoding.Base64Encode (base64Encode)
Returns the base64 decoding of the given content.
encoding.Jsonify (jsonify)
Encodes the given object to JSON.

fmt

Use these functions to print strings within a template or to print messages to the terminal.

fmt.Errorf (errorf)
Log an ERROR from a template.
fmt.Erroridf (erroridf)
Log a suppressible ERROR from a template.
fmt.Print (print)
Prints the default representation of the given arguments using the standard fmt.Print function.
fmt.Printf (printf)
Formats a string using the standard fmt.Sprintf function.
fmt.Println (println)
Prints the default representation of the given argument using the standard fmt.Print function and enforces a line break.
fmt.Warnf (warnf)
Log a WARNING from a template.
fmt.Warnidf (warnidf)
Log a suppressible WARNING from a template.

global

Use these global functions to access page and site data.

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

go template

These are the functions, operators, and statements provided by Go's text/template package.

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

Use these functions to create non-cryptographic hashes.

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

hugo

Use these functions to access information about the Hugo application and the current environment.

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

Use these functions to create an image filter, apply an image filter to an image, and to retrieve image information.

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 the given image using the given 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

These functions provide word inflection features such as singularization and pluralization of English nouns.

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

js

Use these functions to work with JavaScript and TypeScript files.

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

lang

Use these functions to adapt your site to meet language and regional requirements.

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 (T or i18n)
Translates a string using the translation tables in the i18n directory.

math

Use these functions to perform mathematical operations.

math.Abs
Returns the absolute value of the given number.
math.Acos
Returns the arccosine, in radians, of the given number.
math.Add (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 (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.Min
Returns the smaller of all numbers. Accepts scalars, slices, or both.
math.Mod (mod)
Returns the modulus of two integers.
math.ModBool (modBool)
Reports whether the modulus of two integers equals 0.
math.Mul (mul)
Multiplies two or more numbers.
math.Pi
Returns the mathematical constant pi.
math.Pow (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 (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

Use these functions to work with OpenAPI 3 definitions.

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

os

Use these functions to interact with the operating system.

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

partials

Use these functions to call partial templates.

partials.Include (partial)
Executes the given partial template, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output.
partials.IncludeCached (partialCached)
Executes the given template and caches the result, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output.

path

Use these functions to work with file paths.

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

Use these functions to determine a value's data type.

reflect.IsMap
Reports whether the given value is a map.
reflect.IsSlice
Reports whether the given value is a slice.

resources

Use these functions to work with resources.

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 (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 (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

Use these functions to declare a value as safe in the context of Go's html/template package.

safe.CSS (safeCSS)
Declares the given string as a safe CSS string.
safe.HTML (safeHTML)
Declares the given string as a safeHTML string.
safe.HTMLAttr (safeHTMLAttr)
Declares the given key-value pair as a safe HTML attribute.
safe.JS (safeJS)
Declares the given string as a safe JavaScript expression.
safe.JSStr (safeJSStr)
Declares the given string as a safe JavaScript string.
safe.URL (safeURL)
Declares the given string as a safe URL or URL substring.

strings

Use these functions to work with strings.

strings.Chomp (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 (countrunes)
Returns the number of runes in the given string excluding whitespace.
strings.CountWords (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 (findRE)
Returns a slice of strings that match the regular expression.
strings.FindRESubmatch (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 (hasPrefix)
Reports whether the given string begins with the given prefix.
strings.HasSuffix (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 (replace)
Returns a copy of INPUT, replacing all occurrences of OLD with NEW.
strings.ReplaceRE (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 (slicestr)
Returns a substring of the given string, beginning with the start position and ending before the end position.
strings.Split (split)
Returns a slice of strings by splitting the given string by a delimiter.
strings.Substr (substr)
Returns a substring of the given string, beginning with the start position and ending after the given length.
strings.Title (title)
Returns the given string, converting it to title case.
strings.ToLower (lower)
Returns the given string, converting all characters to lowercase.
strings.ToUpper (upper)
Returns the given string, converting all characters to uppercase.
strings.Trim (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 (truncate)
Returns the given string, truncating it to a maximum length without cutting words or leaving unclosed HTML tags.

templates

Use these functions to query the template system.

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.

time

Use these functions to work with time values.

time.AsTime (time)
Returns the given string representation of a date/time value as a time.Time value.
time.Duration (duration)
Returns a time.Duration value using the given time unit and number.
time.Format (dateFormat)
Returns the given date/time as a formatted and localized string.
time.Now (now)
Returns the current local time.
time.ParseDuration
Returns a time.Duration value by parsing the given duration string.

transform

Use these functions to transform values from one format to another.

transform.CanHighlight
Reports whether the given code language is supported by the Chroma highlighter.
transform.Emojify (emojify)
Runs a string through the Emoji emoticons processor.
transform.Highlight (highlight)
Renders code with a syntax highlighter.
transform.HighlightCodeBlock
Highlights code received in context within a code block render hook.
transform.HTMLEscape (htmlEscape)
Returns the given string, escaping special characters by replacing them with HTML entities.
transform.HTMLUnescape (htmlUnescape)
Returns the given string, replacing each HTML entity with its corresponding character.
transform.Markdownify (markdownify)
Renders Markdown to HTML.
transform.Plainify (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 (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

Use these functions to work with URLs.

urls.AbsLangURL (absLangURL)
Returns an absolute URL with a language prefix, if any.
urls.AbsURL (absURL)
Returns an absolute URL.
urls.Anchorize (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.Ref (ref)
Returns the absolute permalink to a page at the given path.
urls.RelLangURL (relLangURL)
Returns a relative URL with a language prefix, if any.
urls.RelRef (relref)
Returns the relative permalink to a page at the given path.
urls.RelURL (relURL)
Returns a relative URL.
urls.URLize (urlize)
Returns the given string, sanitized for usage in a URL.