Template syntax

gotmpl4j implements Go’s text/template syntax. This page is a quick reference; the authoritative specification is the Go documentation.

1. Actions

Anything between {{ and }} is an action. Text outside is copied verbatim.

Hello {{ .name }}, you have {{ .count }} messages.

Trim surrounding whitespace with {{- and -}}:

{{- range .items }}
  - {{ . }}
{{- end }}

2. Pipelines

A pipeline chains commands with |; the result of each stage becomes the last argument of the next:

{{ .name | upper | printf "%q" }}

3. Variables

{{ $name := .user.name }}
{{ $name }}
{{ range $i, $v := .items }}{{ $i }}={{ $v }} {{ end }}

4. Control flow

{{ if .enabled }}on{{ else if .pending }}wait{{ else }}off{{ end }}

{{ with .address }}{{ .city }}, {{ .zip }}{{ end }}

{{ range .items }}{{ . }}{{ else }}no items{{ end }}

range supports break and continue.

5. Defined templates

{{ define "row" }}<td>{{ . }}</td>{{ end }}
{{ template "row" .value }}
{{ block "body" . }}default{{ end }}

6. Go built-in functions

These functions are always available, matching Go’s text/template built-in set. They live in Functions.GO_BUILTINS in gotmpl4j-core.

Function Description

print, printf, println

Formatting, like Go’s fmt.Sprint/Sprintf/Sprintln.

and, or, not

Boolean logic.

eq, ne, lt, le, gt, ge

Comparison; handles mixed numeric types.

index

Element of a map, list, or array by key/index.

slice

Sub-slice of a string, list, or array.

len

Length of a string, map, list, or array.

call

Invoke a function value with arguments.

html, js, urlquery

Escapers for HTML, JavaScript, and URL-query contexts.

7. HTML auto-escaping

For HTML output, enable contextual auto-escaping (a port of Go’s html/template). It inserts the correct escaper for each context — element text, attribute values, URLs, <script>, and <style>:

GoTemplate tpl = GoTemplate.builder().htmlEscaping().build();
tpl.parse("p", "<a href=\"{{ .url }}\">{{ .text }}</a>");

Each interpolation is escaped according to where it appears, defending against XSS without manual escaping in the template.