Template Helpers

Gastro provides 18 built-in template functions available in all templates without registration. You can also add custom helpers.

String Functions

{{ .Name | upper }}        {{/* "ALICE" */}}
{{ .Name | lower }}        {{/* "alice" */}}
{{ .Bio | trim }}          {{/* trims whitespace */}}
{{ .Tags | join ", " }}    {{/* "go, web, ssr" */}}
FunctionDescription
upperConverts string to uppercase
lowerConverts string to lowercase
trimTrims leading and trailing whitespace
joinJoins a slice of strings with a separator
splitSplits a string by separator
containsChecks if a string contains a substring
replaceReplaces occurrences in a string

Safety Functions

These functions mark content as safe for specific contexts, bypassing html/template's automatic escaping. Use them only with trusted content:

{{/* Render trusted HTML */}}
{{ .Body | safeHTML }}

{{/* Safe attribute values */}}
<div class="{{ .Class | safeAttr }}">

{{/* Safe URLs */}}
<a href="{{ .URL | safeURL }}">

{{/* Safe CSS */}}
<div style="{{ .Style | safeCSS }}">

{{/* Safe JS */}}
<script>var x = {{ .Data | safeJS }}</script>
FunctionMarks safe for
safeHTMLHTML content (renders without escaping)
safeAttrHTML attribute values
safeURLURL values in href/src attributes
safeCSSCSS property values
safeJSJavaScript values

Utility Functions

{{/* Default values */}}
{{ .Name | default "Anonymous" }}

{{/* Time formatting */}}
{{ .CreatedAt | timeFormat "Jan 2, 2006" }}

{{/* JSON output */}}
{{ .Config | json }}

{{/* Build maps and lists inline */}}
{{ dict "key" "value" "other" 42 }}
{{ list "a" "b" "c" }}

{{/* String operations */}}
{{ split .Tags "," }}
{{ contains .Title "Go" }}
{{ replace .Text "old" "new" }}
FunctionDescription
defaultReturns value, or fallback if empty/zero
timeFormatFormats a time.Time using Go's layout syntax
jsonJSON-encodes a value
dictCreates a map[string]any from key-value pairs
listCreates a []any from arguments

Custom Helpers

Register custom template functions in your main.go using gastro.WithFuncs():

routes := gastro.Routes(
    gastro.WithFuncs(template.FuncMap{
        "formatEUR": func(cents int) string {
            return fmt.Sprintf("%.2f EUR", float64(cents)/100)
        },
        "slugify": func(s string) string {
            return strings.ToLower(strings.ReplaceAll(s, " ", "-"))
        },
    }),
)

Custom functions are available in all pages and components, just like the built-in helpers.