Skip to content

Instantly share code, notes, and snippets.

@aziis98
Created August 13, 2022 23:42
Show Gist options
  • Save aziis98/790b03ca12772e2c2e7e42832729cb4a to your computer and use it in GitHub Desktop.
Save aziis98/790b03ca12772e2c2e7e42832729cb4a to your computer and use it in GitHub Desktop.
A small cheatsheat of Go Templates

Go Templates Cheat Sheet

Usage

Import text/template or html/template as needed.

tmpl, _ := template.New(“template_name”).Parse(“...”)
tmpl.Name() // => name of current template
tmpl.Execute(...) // => current template
tmpl.ExecuteTemplate(...) // => execute template by name
tmpl = tmpl.Lookup(“template_name”) // => change current template
tmpl.Templates() // => Get defined templates

Templates

Defining template:

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

Using template:

{{ template “template_name” . }}

Block:

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

and is equivalent to

{{  template “content” . }}
{{ define “content” }}
    ...
{{ end }}

Conditionals

{{ if var }}
    ...
{{ else if var }}
    ...
{{ else }}
    ...
{{ end }}

Assignment:

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

With

{{ with .Firstname }}
    Here "." refers to Firstname
{{ end }}

{{ with $firstname := .Firstname }}
    Here "." 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 }}

Common functions

{{ if and cond1 cond2 … }}
{{ if or cond1 cond2 … }}
{{ if not cond }}
{{ len var }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment