Skip to content

4. Built in functions

Matt Mc edited this page Jul 4, 2018 · 1 revision

Some functions are available to you in every template. They may be in invoked as regular functions:

{{ lower("TEST") }} <!-- outputs "test" -->

Or, which may be preferred, they can be invoked as pipelines which also allows chaining:

{{ "test"|upper|trimSpace }} <!-- outputs "TEST" -->

For documentation on how to add your own (global) functions see Jet Template Syntax.

isset()

Can be used to check against truthy or falsy expressions:

{{ isset(.Title) ? .Title : "Title not set" }}

It can also be used to check for map key existence:

{{isset(.["non_existant_key"]) ? "key does exist" : "key does not exist"}}
<!-- will print "key does not exist" -->

The example above uses the context but of course this also works with maps registered on the variable map.

len()

Counts the elements in arrays, channels, slices, maps, and strings. When used on a struct argument it returns the number of fields.

from go's strings package

  • lower (strings.ToLower)
  • upper (strings.ToUpper)
  • hasPrefix (strings.HasPrefix)
  • hasSuffix (strings.HasSuffix)
  • repeat (strings.Repeat)
  • replace (strings.Replace)
  • split (strings.Split)
  • trimSpace (strings.TrimSpace)

escape helper

  • html (html.EscapeString)
  • url (url.QueryEscape)
  • safeHtml (escape HTML)
  • safeJs (escape JavaScript)
  • raw, unsafe (no escaping)
  • writeJson, json to dump variables as JSON strings

on-the-fly map creation

  • map: map(key1, value1, key2, value2) – use with caution because accessing these is slow when used with lots of elements and checked/read in loops.