Created
January 17, 2016 08:29
-
-
Save rohanthewiz/52e1130513d892e5b78a to your computer and use it in GitHub Desktop.
Exercising Go templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"html/template" | |
"os" | |
"strings" | |
) | |
type Person struct { | |
Name string | |
Age int | |
Emails []string | |
Jobs []*Job | |
} | |
type Job struct { | |
Employer string | |
Role string | |
} | |
const templ = `The name is {{.Name}}. | |
{{$name := .Name}} | |
The age is {{.Age}} | |
{{range .Emails}}An email is {{.}} | |
{{end}}----------------------- | |
{{range .Jobs}}{{$name}} is a {{.Role}} at {{if eq .Employer "Box Hill"}}{{.Employer | capitalize}} | |
{{else}}{{.Employer}}{{end}} | |
{{end}}` | |
func main() { | |
// Create some data | |
job1 := Job{Employer: "Monash", Role: "Honorary"} | |
job2 := Job{Employer: "Box Hill", Role: "Head of HE"} | |
person := Person { | |
Name: "Jan", | |
Age: 50, | |
Emails: []string{"[email protected]", "[email protected]"}, | |
Jobs: []*Job{&job1, &job2}, | |
} | |
t := template.New("Person template") // create a container | |
t = t.Funcs(template.FuncMap{"capitalize" : Capitalizer}) // add our custom template function | |
t, err := t.Parse(templ) // load template data into the container | |
checkError(err) | |
err = t.Execute(os.Stdout, person) // apply an object to the template | |
checkError(err) | |
} | |
// Custom pipeline function | |
func Capitalizer(args ...interface{}) string { | |
ok := false | |
var s string | |
if len(args) == 1 { | |
s, ok = args[0].(string) | |
} | |
if !ok { | |
s = fmt.Sprint(args...) | |
} | |
return strings.ToUpper(s) | |
} | |
func checkError(err error) { | |
if err != nil { | |
fmt.Println("Fatal error", err.Error()) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment