Last active
July 13, 2023 20:10
-
-
Save rms1000watt/308ce7e525ebbf5981275981fa002a94 to your computer and use it in GitHub Desktop.
Golang script for using templates with IF and AND
This file contains 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" | |
"os" | |
"text/template" | |
) | |
type Person struct { | |
Name string | |
Age int | |
} | |
type School struct { | |
Students []Person | |
Name string | |
} | |
func main() { | |
templateStr := `Hello World: | |
My Name is: {{.Name}} | |
My Age is: {{.Age}} | |
{{ if and (eq .Age 33) (eq .Name "Mary")}} | |
Verified: I am 33 and my name is Mary. | |
{{ else }} | |
Not verified | |
{{ end }} | |
` | |
templateStr2 := `Hello School: | |
School Name is: {{.Name}} | |
Students are: {{ range $student := .Students }}{{ $student.Name }}-{{ $student.Age }}, {{ end }} | |
` | |
mary := Person{ | |
Name: "Mary", | |
Age: 33, | |
} | |
joe := Person{ | |
Name: "Joe", | |
Age: 33, | |
} | |
school := School{ | |
Name: "Ocean College", | |
Students: []Person{ | |
mary, | |
joe, | |
}, | |
} | |
t := template.New("Template Title...") | |
t, err := t.Parse(templateStr) | |
if err != nil { | |
fmt.Println(err) | |
} | |
t.Execute(os.Stdout, mary) | |
t.Execute(os.Stdout, joe) | |
t, err = template.New("Template 2 Title...").Parse(templateStr2) | |
if err != nil { | |
fmt.Println(err) | |
} | |
t.Execute(os.Stdout, school) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your explanation.