--- aliases: - /layout/functions/ 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 ### 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")}} ### 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 }} ### 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" ### 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/). ### 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 }}` ### pluralize Pluralize the given word with a set of common English pluralization rules. e.g. `{{ "cat" | pluralize }}` → "cats" ### replace Replaces all occurrences of the search string with the replacement string. e.g. `{{ replace "Batman and Robin" "Robin" "Catwoman" }}` → "Batman and Catwoman" ### safeHTML Declares the provided string as a "safe" HTML document fragment so Go html/template will not filter it. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. Example: Given a site-wide `config.toml` that contains this line: copyright = "© 2015 Jane Doe. Some rights reserved." `{{ .Site.Copyright | safeHTML }}` would then output: > © 2015 Jane Doe. Some rights reserved. However, without the `safeHTML` function, html/template assumes `.Site.Copyright` to be unsafe, escaping all HTML tags, rendering the whole string as plain-text like this:### 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" ### 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" ### 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" ## 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 `