Skip to content

Instantly share code, notes, and snippets.

@nikvdp
Created September 22, 2022 06:58
Show Gist options
  • Save nikvdp/d646e0c25874b2c8aff31cc962d5e9ef to your computer and use it in GitHub Desktop.
Save nikvdp/d646e0c25874b2c8aff31cc962d5e9ef to your computer and use it in GitHub Desktop.
golang template cheatsheet

golang text/template cheatsheet. converted from this google doc / reddit post

see also: Go by example

Defining template:

{{ define “template_name” }}         {{ end }}

Using template:

{{ template “template_name” . }}

Block:

{{ block “content” . }}         {{ end }}

Is equivalent to =>         {{  template “content” . }}         {{ define “content” }}         {{ end }}

If:

{{ if var }}                 //…         {{ else if var }}                 //…         {{ else }}                 //…         {{ end }}

Assignment:

{{ $first_name := “arash” }} {{ $first_name = .Name }}

With:

{{ with . Firstname  }} // . refers to Firstname {{ end }}

{{ with $ firstname  := .Firstname }} // . and $firstname both refer to Firstname {{ end }}

Range:

{{ range .Users }}     {{ .Firstname }} {{ end }}

{{ range $user := .Users }}     {{ .Firstname }}     {{ $user.Firstname }}     {{ else }}         No users found {{ end }}

{{ range $index, $user := .Users }} {{ end }}

Functions:

{{ if and cond1 cond2 … }}

{{ if or cond1 cond2 … }}

{{ if not cond }}

{{ len var }}

tmpl, _ := template.New(“template_name”).Parse(“...”)

tmpl.Name()        =>        name of current template

tmpl.Execute(...)        =>        execute current template

tmpl.ExecuteTemplate(...)        =>        execute template by name

tmpl = tmpl.Lookup(“template_name”)        =>        change current template

tmpl.Templates()        =>        Get defined templates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment