利用golang的template模板包进行web开发

前端之家收集整理的这篇文章主要介绍了利用golang的template模板包进行web开发前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
"fmt"
"html/template"
"net/http"
"os"
)

type Person struct {
Name    string
Age     int
Emails  []string
Company string
Role    string
}

type OnlineUser struct {
User      []*Person
LoginTime string
}

func Handler(w http.ResponseWriter,r *http.Request) {
dumx := Person{
Name: "zoro",Age: 27,Emails: []string{"dg@gmail.com","dk@hotmail.com"},Company: "Omron",Role: "SE"}

chxd := Person{Name: "chxd",Emails: []string{"test@gmail.com","d@hotmail.com"}}

onlineUser := OnlineUser{User: []*Person{&dux,&ch}}

//t := template.New("Person template")
//t,err := t.Parse(templ)
t,err := template.ParseFiles("tmpl.html")
checkError(err)

err = t.Execute(w,onlineUser)
checkError(err)
}

func main() {
http.HandleFunc("/",Handler)
http.ListenAndServe(":8888",nil)
}

func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ",err.Error())
os.Exit(1)
}
}
======================================
<html>
		<head>
		</head>
		<body>
			<form action="/test" method="POST">
					{{with .User}}
						{{range .}}
							<input type="radio" name="test" value={{.Name}}/>{{.Name}}<br/>
						{{end}}
					{{end}}
					<input type="submit" value="submit"/>
			</form>
		</body>
</html>

猜你在找的Go相关文章