--- aliases: - /layout/functions/ lastmod: 2015-09-20 date: 2013-07-01 linktitle: Functions toc: true menu: main: parent: layout next: /templates/variables prev: /templates/go-templates title: Hugo Template Functions weight: 20 --- Hugo uses the excellent Go html/template library for its template engine. It is an extremely lightweight engine that provides a very small amount of logic. In our experience, it is just the right amount of logic to be able to create a good static website. Go templates are lightweight but extensible. Hugo has added the following functions to the basic template logic. (Go itself supplies built-in functions, including comparison operators and other basic tools; these are listed in the [Go template documentation](http://golang.org/pkg/text/template/#hdr-Functions).) ## General ### default Checks whether a given value is set and returns a default value if it is not. "Set" in this context means non-zero for numeric types and times; non-zero length for strings, arrays, slices, and maps; any boolean or struct value; or non-nil for any other types. e.g. {{ index .Params "font" | default "Roboto" }} → default is "Roboto" {{ default "Roboto" (index .Params "font") }} → default is "Roboto" ### delimit Loops through any array, slice or map and returns a string of all the values separated by the delimiter. There is an optional third parameter that lets you choose a different delimiter to go between the last two values. Maps will be sorted by the keys, and only a slice of the values will be returned, keeping a consistent output order. Works on [lists](/templates/list/), [taxonomies](/taxonomies/displaying/), [terms](/templates/terms/), [groups](/templates/list/) e.g. // Front matter +++ tags: [ "tag1", "tag2", "tag3" ] +++ // Used anywhere in a template Tags: {{ delimit .Params.tags ", " }} // Outputs Tags: tag1, tag2, tag3 // Example with the optional "last" parameter Tags: {{ delimit .Params.tags ", " " and " }} // Outputs Tags: tag1, tag2 and tag3 ### dict Creates a dictionary `(map[string, interface{})`, expects parameters added in value:object fasion. Invalid combinations like keys that are not strings or uneven number of parameters, will result in an exception thrown. Useful for passing maps to partials when adding to a template. e.g. Pass into "foo.html" a map with the keys "important, content" {{$important := .Site.Params.SomethingImportant }} {{range .Site.Params.Bar}} {{partial "foo" (dict "content" . "important" $important)}} {{end}} "foo.html" Important {{.important}} {{.content}} or create a map on the fly to pass into {{partial "foo" (dict "important" "Smiles" "content" "You should do more")}} ### slice `slice` allows you to create an array (`[]interface{}`) of all arguments that you pass to this function. One use case is the concatenation of elements in combination with `delimit`: ```html {{ delimit (slice "foo" "bar" "buzz") ", " }} ``` ### shuffle `shuffle` returns a random permutation of a given array or slice, e.g. ```html {{ shuffle (seq 1 5) }} {{ shuffle (slice "foo" "bar" "buzz") }} ``` ### echoParam Prints a parameter if it is set. e.g. `{{ echoParam .Params "project_url" }}` ### eq Returns true if the parameters are equal. e.g. {{ if eq .Section "blog" }}current{{ end }} ### first Slices an array to only the first _N_ elements. Works on [lists](/templates/list/), [taxonomies](/taxonomies/displaying/), [terms](/templates/terms/), [groups](/templates/list/) e.g. {{ range first 10 .Data.Pages }} {{ .Render "summary" }} {{ end }} ### jsonify Encodes a given object to JSON. e.g. {{ dict "title" .Title "content" .Plain | jsonify }} ### last Slices an array to only the last _N_ elements. Works on [lists](/templates/list/), [taxonomies](/taxonomies/displaying/), [terms](/templates/terms/), [groups](/templates/list/) e.g. {{ range last 10 .Data.Pages }} {{ .Render "summary" }} {{ end }} ### after Slices an array to only the items after the Nth item. Use this in combination with `first` to use both halves of an array split at item _N_. Works on [lists](/templates/list/), [taxonomies](/taxonomies/displaying/), [terms](/templates/terms/), [groups](/templates/list/) e.g. {{ range after 10 .Data.Pages }} {{ .Render "title" }} {{ end }} ### getenv Returns the value of an environment variable. Takes a string containing the name of the variable as input. Returns an empty string if the variable is not set, otherwise returns the value of the variable. Note that in Unix-like environments, the variable must also be exported in order to be seen by `hugo`. e.g. {{ getenv "HOME" }} ### in Checks if an element is in an array (or slice) and returns a boolean. The elements supported are strings, integers and floats (only float64 will match as expected). In addition, it can also check if a substring exists in a string. e.g. {{ if in .Params.tags "Git" }}Follow me on GitHub!{{ end }} or {{ if in "this string contains a substring" "substring" }}Substring found!{{ end }} ### intersect Given two arrays (or slices), this function will return the common elements in the arrays. The elements supported are strings, integers and floats (only float64). A useful example of this functionality is a 'similar posts' block. Create a list of links to posts where any of the tags in the current post match any tags in other posts. e.g.
Function | Description | Example |
---|---|---|
add |
Adds two integers. | {{add 1 2}} → 3 |
div |
Divides two integers. | {{div 6 3}} → 2 |
mod |
Modulus of two integers. | {{mod 15 3}} → 0 |
modBool |
Boolean of modulus of two integers. true if modulus is 0. |
{{modBool 15 3}} → true |
mul |
Multiplies two integers. | {{mul 2 3}} → 6 |
sub |
Subtracts two integers. | {{sub 3 2}} → 1 |
Blockhead
\n"}}` → `"Blockhead
"` ### dateFormat Converts the textual representation of the datetime into the other form or returns it of Go `time.Time` type value. These are formatted with the layout string. e.g. `{{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }}` → "Wednesday, Jan 21, 2015" ### emojify Runs the string through the Emoji emoticons processor. The result will be declared as "safe" so Go templates will not filter it. See the [Emoji cheat sheet](http://www.emoji-cheat-sheet.com/) for available emoticons. e.g. `{{ "I :heart: Hugo" | emojify }}` ### highlight Takes a string of code and a language, uses Pygments to return the syntax highlighted code in HTML. Used in the [highlight shortcode](/extras/highlighting/). ### htmlEscape HtmlEscape returns the given string with the critical reserved HTML codes escaped, such that `&` becomes `&` and so on. It escapes only: `<`, `>`, `&`, `'` and `"`. Bear in mind that, unless content is passed to `safeHTML`, output strings are escaped usually by the processor anyway. e.g. `{{ htmlEscape "Hugo & Caddy > Wordpress & Apache" }} → "Hugo & Caddy > Wordpress & Apache"` ### htmlUnescape HtmlUnescape returns the given string with html escape codes un-escaped. This un-escapes more codes than `htmlEscape` escapes, including `#` codes and pre-UTF8 escapes for accented characters. It defers completely to the Go `html.UnescapeString` function, so functionality is consistent with that codebase. Remember to pass the output of this to `safeHTML` if fully unescaped characters are desired, or the output will be escaped again as normal. e.g. `{{ htmlUnescape "Hugo & Caddy > Wordpress & Apache" }} → "Hugo & Caddy > Wordpress & Apache"` ### humanize Humanize returns the humanized version of an argument with the first letter capitalized. If the input is either an int64 value or the string representation of an integer, humanize returns the number with the proper ordinal appended. e.g. ``` {{humanize "my-first-post"}} → "My first post" {{humanize "myCamelPost"}} → "My camel post" {{humanize "52"}} → "52nd" {{humanize 103}} → "103rd" ``` ### lower Converts all characters in string to lowercase. e.g. `{{lower "BatMan"}}` → "batman" ### markdownify Runs the string through the Markdown processor. The result will be declared as "safe" so Go templates will not filter it. e.g. `{{ .Title | markdownify }}` ### plainify Strips any HTML and returns the plain text version. e.g. `{{ "BatMan" | plainify }}` → "BatMan" ### pluralize Pluralize the given word with a set of common English pluralization rules. e.g. `{{ "cat" | pluralize }}` → "cats" ### findRE Returns a list of strings that match the regular expression. By default all matches will be included. The number of matches can be limitted with an optional third parameter. The example below returns a list of all second level headers (`### safeHTMLAttr Declares the provided string as a "safe" HTML attribute from a trusted source, for example, ` dir="ltr"`, so Go html/template will not filter it. Example: Given a site-wide `config.toml` that contains this menu entry: [[menu.main]] name = "IRC: #golang at freenode" url = "irc://irc.freenode.net/#golang" * `` ⇒ `` (Bad!) * `` ⇒ `` (Good!) ### safeCSS Declares the provided string as a known "safe" CSS string so Go html/templates will not filter it. "Safe" means CSS content that matches any of: 1. The CSS3 stylesheet production, such as `p { color: purple }`. 2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`. 3. CSS3 declaration productions, such as `color: red; margin: 2px`. 4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`. Example: Given `style = "color: red;"` defined in the front matter of your `.md` file: * `© 2015 Jane Doe. <a href="http://creativecommons.org/licenses/by/4.0/">Some rights reserved</a>.
…
` ⇒ `…
` (Good!) * `…
` ⇒ `…
` (Bad!) Note: "ZgotmplZ" is a special value that indicates that unsafe content reached a CSS or URL context. ### safeJS Declares the provided string as a known "safe" Javascript string so Go html/templates will not escape it. "Safe" means the string encapsulates a known safe EcmaScript5 Expression, for example, `(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: * `` ⇒ `` (Good!) * `` ⇒ `` (Bad!) ### singularize Singularize the given word with a set of common English singularization rules. e.g. `{{ "cats" | singularize }}` → "cat" ### slicestr Slicing in `slicestr` is done by specifying a half-open range with two indices, `start` and `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. e.g. * `{{slicestr "BatMan" 3}}` → "Man" * `{{slicestr "BatMan" 0 3}}` → "Bat" ### split Split a string into substrings separated by a delimiter. e.g. * `{{split "tag1,tag2,tag3" "," }}` → ["tag1" "tag2" "tag3"] ### string Creates a `string`. e.g. * `{{string "BatMan"}}` → "BatMan" ### substr Extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. 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. In addition, borrowing from the extended behavior described at http://php.net/substr, if `length` is given and is negative, then that many characters will be omitted from the end of string. e.g. * `{{substr "BatMan" 0 -3}}` → "Bat" * `{{substr "BatMan" 3 3}}` → "Man" ### hasPrefix HasPrefix tests whether a string begins with prefix. * `{{ hasPrefix "Hugo" "Hu" }}` → true ### title Converts all characters in string to titlecase. e.g. `{{title "BatMan"}}` → "Batman" ### trim Returns a slice of the string with all leading and trailing characters contained in cutset removed. e.g. `{{ trim "++Batman--" "+-" }}` → "Batman" ### upper Converts all characters in string to uppercase. e.g. `{{upper "BatMan"}}` → "BATMAN" ### countwords `countwords` tries to convert the passed content to a string and counts each word in it. The template functions works similar to [.WordCount]({{< relref "templates/variables.md#page-variables" >}}). ```html {{ "Hugo is a static site generator." | countwords }} ``` ### countrunes Alternatively to counting all words , `countrunes` determines the number of runes in the content and excludes any whitespace. This can become useful if you have to deal with CJK-like languages. ```html {{ "Hello, 世界" | countrunes }} ``` ### md5 `md5` hashes the given input and returns its MD5 checksum. ```html {{ md5 "Hello world, gophers!" }} ``` This can be useful if you want to use Gravatar for generating a unique avatar: ```html ``` ### sha1 `sha1` hashes the given input and returns its SHA1 checksum. ```html {{ sha1 "Hello world, gophers!" }} ``` ## Internationalization ### i18n This translates a piece of content based on your `i18n/en-US.yaml` (and friends) files. You can use the [go-i18n](https://github.com/nicksnyder/go-i18n) tools to manage your translations. The translations can exist in both the theme and at the root of your repository. e.g.: `{{ i18n "translation_id" }}` ### T `T` is an alias to `i18n`. E.g. `{{ T "translation_id" }}`. >>>>>>> Add multilingual support in Hugo ## Times ### time `time` converts a timestamp string into a [`time.Time`](https://godoc.org/time#Time) structure so you can access its fields. E.g. * `{{ time "2016-05-28" }}` → "2016-05-28T00:00:00Z" * `{{ (time "2016-05-28").YearDay }}` → 149 * `{{ mul 1000 (time "2016-05-28T10:30:00.00+10:00").Unix }}` → 1464395400000 (Unix time in milliseconds) ## URLs ### absURL, relURL Both `absURL` and `relURL` considers the configured value of `baseURL`, so given a `baseURL` set to `http://mysite.com/hugo/`: * `{{ "mystyle.css" | absURL }}` → "http://mysite.com/hugo/mystyle.css" * `{{ "mystyle.css" | relURL }}` → "/hugo/mystyle.css" * `{{ "http://gohugo.io/" | relURL }}` → "http://gohugo.io/" * `{{ "http://gohugo.io/" | absURL }}` → "http://gohugo.io/" The last two examples may look funky, but is useful if you, say, have a list of images, some of them hosted externally, some locally: ``` ``` The above also exploits the fact that the Go template parser JSON-encodes objects inside `script` tags. **Note:** These functions are smart about missing slashes, but will not add one to the end if not present. ### ref, relref Looks up a content page by relative path or logical name to return the permalink (`ref`) or relative permalink (`relref`). Requires a Node or Page object (usually satisfied with `.`). Used in the [`ref` and `relref` shortcodes]({{% ref "extras/crossreferences.md" %}}). e.g. {{ ref . "about.md" }} ### 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. [RFC 3986]: http://tools.ietf.org/html/rfc3986 Without `safeURL`, only the URI schemes `http:`, `https:` and `mailto:` are considered safe by Go. If any other URI schemes, e.g. `irc:` and `javascript:`, are detected, the whole URL would be replaced with `#ZgotmplZ`. This is to "defang" any potential attack in the URL, rendering it useless. Example: Given a site-wide `config.toml` that contains this menu entry: [[menu.main]] name = "IRC: #golang at freenode" url = "irc://irc.freenode.net/#golang" The following template: would produce `