您的位置:首页 > 编程语言 > Go语言

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

2013-03-07 09:01 381 查看
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", Age: 27, 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: