Templates

This commit is contained in:
Meutel 2017-07-25 20:05:00 +02:00
parent 1ccc6007ed
commit a030e81501
3 changed files with 70 additions and 0 deletions

1
.gitignore vendored
View File

@ -53,3 +53,4 @@ chatserver/chatserver
example-httptcp/example-httptcp
example-httpserver/example-httpserver
http-router/http-router
tpl-text/tpl-text

51
tpl-text/main.go Normal file
View File

@ -0,0 +1,51 @@
package main
import (
"log"
"os"
//"text/template"
"html/template"
)
type Data struct {
MyTitle string
Lst []int
Thing interface{}
}
func main() {
var err error
//tpl, err := template.ParseFiles("tpl.html")
tpl := template.New("tpl.html")
tpl = tpl.Funcs(template.FuncMap{
"myFunc": func(s string) string {
return s + s
},
})
tpl, err = tpl.ParseFiles("tpl.html")
if err != nil {
log.Fatalln(err)
}
/*
data := map[string]string{
"myTitle": "plop",
}
data := []int{1, 2, 3}
data := map[string]interface{}{
"myTitle": "plop",
"lst": []int{1, 2, 3},
}
*/
data := Data{
//"plop",
"<script>alert('hi!')</script>",
[]int{1, 2, 3},
template.HTML("<script>alert('hi!')</script>"),
}
err = tpl.Execute(os.Stdout, data)
if err != nil {
log.Fatalln(err)
}
}

18
tpl-text/tpl.html Normal file
View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>{{ .MyTitle }}</h1>
<h2>{{ myFunc "hello" }}</h2>
<ul>
{{ range .Lst }}
<li>{{ . }}</li>
{{ else }}
<li>VIDE</li>
{{ end }}
</ul>
<p>{{ .Thing }}</p>
</body>
</html>