How to Use If-Else and Switch Loop Inside HTML Template in Golang
-
Use the
if-elseLoop Inside HTML Templates in Golang -
Use the
switchLoop Inside HTML Template in Golang
HTML template is a Golang (Go) package that supports data-driven templates for creating secure HTML outputs against code injection. One significant advantage of utilizing HTML/template is that it generates safe, escaped HTML output using contextual auto-escaping.
As a result, anytime the output is HTML, the HTML template package should always be used instead of a text template. Let’s look at a few examples of utilizing if-else and switch in the HTML template.
Use the if-else Loop Inside HTML Templates in Golang
In this example, we create two structs to hold the data from our ToDo list items: ToDo and PageData. The defined HTML template, tmpl, is created and parsed.
Finally, we render our HTML by giving it to the Execute() function, the data, and the parsed HTML template.
Code:
package main
import (
"html/template"
"log"
"os"
)
type Todo struct {
Title string
Done bool
}
type PageData struct {
PageTitle string
Todos []Todo
}
func main() {
const tmpl = `
<h1>{{.PageTitle}}</h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li>{{.Title}} ✔</li>
{{else}}
<li>{{.Title}}</li>
{{end}}
{{end}}
</ul>`
t, err := template.New("webpage").Parse(tmpl)
if err != nil {
log.Fatal(err)
}
data := PageData{
PageTitle: "Personal TODO list",
Todos: []Todo{
{Title: "Task 1", Done: true},
{Title: "Task 2", Done: false},
{Title: "Task 3", Done: false},
},
}
t.Execute(os.Stdout, data)
}
Output:
Personal TODO list
Task 1 ✔
Task 2
Task 3
Use the switch Loop Inside HTML Template in Golang
Code:
package main
import (
"fmt"
"html/template"
"os"
)
func main() {
const (
paragraph_hypothesis = 1 << iota
paragraph_attachment = 1 << iota
paragraph_menu = 1 << iota
)
const text = "{{.Paratype | printpara}}\n"
type Paragraph struct {
Paratype int
}
var paralist = []*Paragraph{
&Paragraph{paragraph_hypothesis},
&Paragraph{paragraph_attachment},
&Paragraph{paragraph_menu},
}
t := template.New("testparagraphs")
printPara := func(paratype int) string {
text := ""
switch paratype {
case paragraph_hypothesis:
text = "This is a hypothesis testing\n"
case paragraph_attachment:
text = "This is using switch case\n"
case paragraph_menu:
text = "Menu\n1:\n2:\n3:\n\nPick any option:\n"
}
return text
}
template.Must(t.Funcs(template.FuncMap{"printpara": printPara}).Parse(text))
for _, p := range paralist {
err := t.Execute(os.Stdout, p)
if err != nil {
fmt.Println("executing template:", err)
}
}
}
Output:
This is a hypothesis testing
This is using switch case
Menu
1:
2:
3:
Pick any option:
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe