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 |
|---|---|
|
Formatting, like Go’s |
|
Boolean logic. |
|
Comparison; handles mixed numeric types. |
|
Element of a map, list, or array by key/index. |
|
Sub-slice of a string, list, or array. |
|
Length of a string, map, list, or array. |
|
Invoke a function value with arguments. |
|
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.