Skip to content

Instantly share code, notes, and snippets.

@suntong
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suntong/3539307ef77ddee95f10 to your computer and use it in GitHub Desktop.
Save suntong/3539307ef77ddee95f10 to your computer and use it in GitHub Desktop.
Go Template Example
package main
import (
"bytes"
"os"
"text/template"
)
type Person struct {
Name string //exported field since it begins with a capital letter
}
func main() {
t := template.New("hello template") //create a new template with some name
t, _ = t.Parse("hello {{.Name}}!\n") //parse some content and generate a template, which is an internal representation
p := Person{Name: "Mary"} //define an instance with required field
t.Execute(os.Stdout, p) //merge template ‘t’ with content of ‘p’
type dict struct {
// struct fields must be public
Title string
Release int
}
params := dict{Title: "Go", Release: 60}
t, _ = template.New("template_name").Parse(
"<h1>{{.Title}}</h1>r{{.Release}}\n")
buf := new(bytes.Buffer)
t.Execute(buf, params)
print(buf.String())
t = template.New("template test")
t = template.Must(t.Parse("This is just static text. \n{{\"This is pipeline data - because it is evaluated within the double braces.\"}} {{`So is this, but within reverse quotes.`}}\n"))
t.Execute(os.Stdout, nil)
}
/*
hello Mary!
This is just static text.
This is pipeline data - because it is evaluated within the double braces. So is this, but within reverse quotes.
<h1>Go</h1>r60
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment