HUGO
Menu
GitHub 89810 stars Mastodon

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

Returns the given value converted to a decimal floating-point number (base 10).

cast.ToInt

Returns the given value converted to a decimal integer (base 10).

cast.ToString

Returns the given value converted to a string.

collections

Use these functions to manipulate and query maps, slices, and strings.

collections.After

Returns a slice containing the elements after the first N elements of the given slice.

collections.Append

Returns a slice by adding one or more elements, or an entire second slice, to the end of the given slice.

collections.Apply

Returns a slice by transforming each element of the given slice using a specific function and parameters.

collections.Complement

Returns a slice by identifying elements in the last given slice that do not appear in any of the preceding slices.

collections.D

Returns a sorted slice of unique random integers based on a given seed, count, and maximum value.

collections.Delimit

Returns a string by joining the values of the given slice or map with a delimiter.

collections.Dictionary

Returns a map created from the given key-value pairs.

collections.First

Returns the first N elements of the given slice or string.

collections.Group

Returns a map by grouping the given page collection (slice) by a specific key.

collections.In

Reports whether a value exists within the given slice or string.

collections.Index

Returns an element or value from the given slice or map at the specified key(s).

collections.Intersect

Returns a slice containing the common elements found in two given slices, in the same order as the first slice.

collections.IsSet

Reports whether a specific key or index exists in the given map or slice.

collections.KeyVals

Returns a KeyVals struct by pairing a given key and values.

collections.Last

Returns the last N elements of the given slice or string.

collections.Merge

Returns a map by combining two or more given maps.

collections.NewScratch

Returns a locally scoped persistent data structure for storing and manipulating keyed values.

collections.Querify

Returns a URL query string from the given map, slice, or sequence of key-value pairs.

collections.Reverse

Returns a slice by reversing the order of elements in the given slice.

collections.Seq

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.

collections.Shuffle

Returns a slice by randomizing the element order of the given slice.

collections.Slice

Returns a slice created from the given values.

collections.Sort

Returns a sorted map or slice by reordering the given collection by a key and order.

collections.SymDiff

Returns a slice containing the symmetric difference of two given slices.

collections.Union

Returns a slice containing the unique elements from two given slices.

collections.Uniq

Returns a slice by removing duplicate elements from the given slice.

collections.Where

Returns a slice by filtering the given slice based on a key, operator, and value.

compare

Use these functions to compare two or more values.

compare.Conditional

Returns one of two arguments depending on the value of the control argument.

compare.Default

Returns the second argument if set, else the first argument.

compare.Eq

Returns the boolean truth of arg1 == arg2 || arg1 == arg3.

compare.Ge

Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3.

compare.Gt

Returns the boolean truth of arg1 > arg2 && arg1 > arg3.

compare.Le

Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3.

compare.Lt

Returns the boolean truth of arg1 < arg2 && arg1 < arg3.

compare.Ne

Returns the boolean truth of arg1 != arg2 && arg1 != arg3.

crypto

Use these functions to create cryptographic hashes.

crypto.Hash

Returns the checksum of the given input, encoded to a hexadecimal string, using the given hash algorithm.

crypto.HMAC

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

crypto.MD5

Returns the MD5 checksum of the given input, encoded to a hexadecimal string.

crypto.SHA1

Returns the SHA1 checksum of the given input, encoded to a hexadecimal string.

crypto.SHA256

Returns the SHA256 checksum of the given input, encoded to a hexadecimal string.

css

Use these functions to work with CSS and Sass files.

css.Build

Returns a resource created by bundling, transforming, and minifying the given CSS resource.

css.ChromaStyles

Returns a CSS stylesheet for the syntax highlighter.

css.PostCSS

Returns a resource created by processing the given CSS resource with PostCSS.

css.Quoted

Returns the given string, setting its data type to indicate that it must be quoted when used in CSS.

css.Sass

Returns a resource created by transpiling the given Sass resource to CSS.

css.TailwindCSS

Returns a resource created by processing the given resource with the Tailwind CSS CLI.

css.Unquoted

Returns the given string, setting its data type to indicate that it must not be quoted when used in CSS.

debug

Use these functions to debug your templates.

debug.Dump

Returns an object dump as a string.

debug.Timer

Returns a named timer used to measure and report elapsed execution time to the console.

debug.VisualizeSpaces

Returns the given string with spaces replaced by a visible string.

diagrams

Use these functions to render diagrams.

diagrams.Goat

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

encoding

Use these functions to encode and decode data.

encoding.Base64Decode

Returns the base64 decoding of the given content.

encoding.Base64Encode

Returns the base64 decoding of the given content.

encoding.HexDecode

Returns the hexadecimal decoding of the given content.

encoding.HexEncode

Returns the hexadecimal encoding of the given content.

encoding.Jsonify

Returns the given object encoded to JSON.

fmt

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

fmt.Errorf

Logs an ERROR from a template.

fmt.Erroridf

Logs a suppressible ERROR from a template.

fmt.Print

Returns the default string representation of the given arguments.

fmt.Printf

Returns a string formatted according to the given format specifier.

fmt.Println

Returns the default string representation of the given arguments, followed by a line break.

fmt.Warnf

Logs a WARNING from a template.

fmt.Warnidf

Logs a suppressible WARNING from a template.

global

Use these global functions to access page and site data.

page

Returns the Page object of the current page, accessible from any context.

site

Returns the Site object of the current site, accessible from any context.

go template

Use these functions and statements to write conditionals, loops, and other template logic.

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

Stops the innermost range iteration and bypasses any remaining iterations.

continue

Stops the innermost range iteration and continues with 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

Terminates execution of the current template and, when used within a partial template, 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

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.Data

Returns a data structure composed from the files in the data directory.

hugo.Deps

Returns a slice of project dependencies, either modules or local theme components.

hugo.Environment

Returns the current running environment.

hugo.Generator

Returns 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.Sites

Returns a collection of all sites for all dimensions.

hugo.Store

Returns a globally scoped persistent data structure for storing and manipulating keyed values.

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

Returns a new image resource created by applying 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

Returns an image resource containing a QR code encoded from the given text using the specified options.

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

Use these functions for word inflection, such as singularization and pluralization of English nouns.

inflect.Humanize

Returns the humanized version of the input with the first letter capitalized.

inflect.Pluralize

Returns the plural form of the given word according to a set of common English pluralization rules.

inflect.Singularize

Returns the singular form of the given word according to a set of common English singularization rules.

js

Use these functions to work with JavaScript and TypeScript files.

js.Babel

Returns a resource created by transpiling the given JavaScript resource using Babel.

js.Batch

Returns a batcher used to build JavaScript bundle groups with global code splitting and flexible hooks/runners setup.

js.Build

Returns a resource created by bundling, transpiling, tree shaking, and minifying the given JavaScript resource.

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

Returns a copy of the given page collection with missing translations filled in from another page collection.

lang.Translate

Returns a translated 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

Returns the result of adding one or more numbers to the first number.

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

Returns a global counter value, incrementing it each time the function is called.

math.Div

Returns the result of dividing 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

Returns the result of multiplying the first number by one 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

Returns the result of subtracting 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

Returns the given radian value converted to degrees.

math.ToRadians

Returns the given degree value converted to radians.

openapi3

Use these functions to work with OpenAPI 3 definitions.

openapi3.Unmarshal

Returns an OpenAPI 3 Description unmarshaled from the given resource.

os

Use these functions to interact with the operating system.

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

Use these functions to call partial templates.

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

Use these functions to work with file paths.

path.Base

Returns the last element of the given path, after replacing path separators with slashes (/).

path.BaseName

Returns the last element of the given path with its extension removed, if present, after replacing path separators with slashes (/).

path.Clean

Returns the shortest path name equivalent to the given path, after replacing path separators with slashes (/).

path.Dir

Returns all but the last element of the given path, after replacing path separators with slashes (/).

path.Ext

Returns the file extension of the given path, after replacing path separators with slashes (/).

path.Join

Returns the shortest path name equivalent to the given path elements joined into a single path, after replacing path separators with slashes (/).

path.Split

Returns the directory and file name components of the given path, split immediately following the final slash, after replacing path separators with slashes (/).

reflect

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

reflect.IsImageResource

Reports whether the given value is a Resource object representing an image as defined by its media type.

reflect.IsImageResourceProcessable

Reports whether the given value is a Resource object representing an image from which Hugo can extract dimensions and perform processing such as converting, resizing, cropping, or filtering.

reflect.IsImageResourceWithMeta

Reports whether the given value is a Resource object representing an image from which Hugo can extract dimensions and, if present, Exif, IPTC, and XMP data.

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

Use these functions to work with resources.

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

Returns a copy of the given resource at the target path.

resources.ExecuteAsTemplate

Returns a resource created from a Go template, parsed and executed with the given context.

resources.Fingerprint

Returns a fingerprinted resource, created by cryptographically hashing 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

Returns a minified version of the given resource.

resources.PostProcess

Returns a resource that is processed after the build.

resources.Publish

Returns the given resource after publishing it.

safe

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

safe.CSS

Returns the given string declared as safe CSS.

safe.HTML

Returns the given string declared as safe HTML.

safe.HTMLAttr

Returns the given key-value pair declared as a safe HTML attribute.

safe.JS

Returns the given string declared as a safe JavaScript expression.

safe.JSStr

Returns the given string declared as a safe JavaScript string.

safe.URL

Returns the given string declared as a safe URL or URL substring.

strings

Use these functions to work with strings.

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, converting the first character to uppercase.

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 the given string repeated the given number of times.

strings.Replace

Returns the given string, replacing all occurrences of OLD with NEW.

strings.ReplacePairs

Returns the given string, with multiple replacements performed in a single pass using a slice of old and new string pairs.

strings.ReplaceRE

Returns the given string, 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

Use these functions to query the template system.

templates.Current

Returns information about the currently executing template.

templates.Defer

Defers execution of a template until 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

Use these functions to work with time values.

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

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

transform.CanHighlight

Reports whether the given language is supported for syntax highlighting.

transform.Emojify

Returns the given string with emoji shortcodes replaced by their corresponding emoji characters.

transform.Highlight

Returns the given code rendered with a syntax highlighter.

transform.HighlightCodeBlock

Returns highlighted 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

Returns the given HTML converted to Markdown.

transform.HTMLUnescape

Returns the given string, replacing each HTML entity with its corresponding character.

transform.Markdownify

Returns the given Markdown rendered to HTML.

transform.Plainify

Returns a string with all HTML tags removed.

transform.PortableText

Returns the given Portable Text converted to Markdown.

transform.Remarshal

Returns a string of serialized data in the specified format, marshaled from a string of serialized data or a map.

transform.ToMath

Returns the given mathematical markup, written in the LaTeX language, rendered to HTML.

transform.Unmarshal

Returns a map or an array parsed from serialized data in CSV, JSON, TOML, YAML, or XML format.

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

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

Returns a URL string created by joining the provided elements and cleaning the result of any ./ or ../ elements, or an empty string if the argument list is empty.

urls.Parse

Returns a URL structure parsed from the given URL.

urls.PathEscape

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.PathUnescape

Returns the given string, replacing all percent-encoded sequences with the corresponding unescaped characters.

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.