1、html/template创建基础静态模板

package main
import(
    "html/template"
    "log"
    "os"
)
func main(){
    tmpl,err := template.New("go-web").Parse(`Hello World!`)//先创建一个template对象
    if err != nil {
        log.Fatalf("Parse:%v",err)//fatalf格式化字符串,打印错误
    }
    err = tmpl.Execute(os.Stdout,nil) //调用方法Execute,两个参数:目的地,data先等于nil
    if err != nil{
        log.Fatal("Execute: %v", err)
    }
}
go run test.go 输出:
Hello World!

2、输出动态模板

package main
import(
    "html/template"
    "log"
    "os"
)
func main(){
    tmpl,err := template.New("go-web").Parse(`Hello World!,{{.}}`)//先创建能够根据输入数据的不同,产生不同的效果的动态模板{{}}, “.”代表跟对象“go web”
    if err != nil {
        log.Fatalf("Parse:%v",err)//fatalf格式化字符串,打印错误
    }
    err = tmpl.Execute(os.Stdout,"go web") //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
    if err != nil{
        log.Fatal("Execute: %v", err)
    }
}
go run test.go 输出:
Hello World!,go web

package main
import(
    "html/template"
    "log"
    "os"
)
type Package struct {//自定义的传入类型Package
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    tmpl,err := template.New("go-web").Parse(`Hello World!,{{.}}`)//先创建能够根据输入数据的不同,产生不同的效果的动态模板{{}}, .代表跟对象
    if err != nil {
        log.Fatalf("Parse:%v",err)//fatalf格式化字符串,打印错误
    }
    err = tmpl.Execute(os.Stdout,&Package{ //自定义的传入类型Package
        Name :"go-web",
        NumFuncs:12,
        NumVars:1200,

    }) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
    if err != nil{
        log.Fatal("Execute: %v", err)
    }
}
go run test.go 输出:
Hello World!,{go-web 12 1200}

如何将模板渲染的结果输出到stdout呢?
package main
import(
    "html/template"
    "log"
    "os"
)
type Package struct {
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    tmpl,err := template.New("go-web").Parse(` 
        Package name: {{.Name}}  //通过反射寻找方法,字段或者函数,Name必须公开,必须首字母大写,
        Number of functions: {{.NumFuncs}} 
        Number of variables: {{.NumVars}}
        `)//先创建能够根据输入数据的不同,产生不同的效果的动态模板{{}}, .代表跟对象
    if err != nil {
        log.Fatalf("Parse:%v",err)//fatalf格式化字符串,打印错误
    }
    err = tmpl.Execute(os.Stdout,&Package{
        Name :"go-web",
        NumFuncs:12,
        NumVars:1200,

    }) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
    if err != nil{
        log.Fatal("Execute: %v", err)
    }
}
go run test.go 输出:
        Package name: go-web
        Number of functions: 12 
        Number of variables: 1200

3、模板结果输出到http响应流,通过浏览器访问

package main
import(
    "html/template"
    "log"
    "net/http"
    "fmt"
)
type Package struct {
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        tmpl,err := template.New("go-web").Parse(`
        Package name: {{.Name}}
        Number of functions: {{.NumFuncs}} 
        Number of variables: {{.NumVars}}
        `)//先创建能够根据输入数据的不同,产生不同的效果的动态模板{{}}, .代表跟对象
        if err != nil {
            fmt.Fprintf(writer,"Parse:%v",err)
            return
        }
        err = tmpl.Execute(writer,&Package{
            Name :"go-web",
            NumFuncs:12,
            NumVars:1200,

        }) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
        if err != nil{
            fmt.Fprintf(writer,"Execute:%v",err)
            return
        }
    })
    log.Println("Starting Server....")
    log.Fatal(http.ListenAndServe(":4000",nil))
}
go run test.go 输出:
2018/07/10 10:38:40 Starting Server....

浏览器访问:http://localhost:4000/
Go编程基础5-基础模板用法_第1张图片

4、从文件中读取模板的方法

package main
import(
    "html/template"
    "log"
    "net/http"
    "fmt"
)
type Package struct {
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        tmpl,err := template.ParseFiles("main.tmpl")
        if err != nil {
            fmt.Fprintf(writer,"ParseFiles:%v",err)
            return
        }
        err = tmpl.Execute(writer,&Package{
            Name :"go-web",
            NumFuncs:14,
            NumVars:1200,

        }) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
        if err != nil{
            fmt.Fprintf(writer,"Execute:%v",err)
            return
        }
    })
    log.Println("Starting Server....")
    log.Fatal(http.ListenAndServe(":4000",nil))
}
然后编辑本地main.tmpl文件:
➜  test pwd
/Users/daixuan/qbox/test
➜  test vim main.tmpl
Package name: {{.Name}}
Number of functions: {{.NumFuncs}}
Number of variables: {{.NumVars}}
go run test.go 输出:
2018/07/10 10:52:56 Starting Server....

浏览器访问:http://localhost:4000/
Go编程基础5-基础模板用法_第2张图片

5、http.request 如何使用模板打印出结构中我们所需要的内容

➜  test vim main.tmpl
Method: {{.Method}}

package main
import(
    "html/template"
    "log"
    "net/http"
    "fmt"
)
type Package struct {
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        tmpl,err := template.ParseFiles("main.tmpl")
        if err != nil {
            fmt.Fprintf(writer,"ParseFiles:%v",err)
            return
        }
        err = tmpl.Execute(writer,request) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
        if err != nil{
            fmt.Fprintf(writer,"Execute:%v",err)
            return
        }
    })
    log.Println("Starting Server....")
    log.Fatal(http.ListenAndServe(":4000",nil))
}
go run test.go 输出:
2018/07/10 11:01:28 Starting Server....

浏览器访问:http://localhost:4000/ 打印出了Method:GET
Go编程基础5-基础模板用法_第3张图片

修改main.tmpl
Method: {{.Method}}
URL: {{.URL.Path}}

浏览器访问:http://localhost:4000/ 打印出Path: /
Go编程基础5-基础模板用法_第4张图片

打印User-Agent

修改main.tmpl
Method: {{.Method}}
Path: {{.URL.Path}}
Header: {{.Header.Get "User-Agent"}}

package main
import(
    "html/template"
    "log"
    "net/http"
    "fmt"
)
type Package struct {
    Name string
    NumFuncs int
    NumVars int
}
func main(){
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        tmpl,err := template.ParseFiles("main.tmpl")
        if err != nil {
            fmt.Fprintf(writer,"ParseFiles:%v",err)
            return
        }
        err = tmpl.Execute(writer,request) //调用方法Execute,两个参数:目的地,data先等于go web,此时跟对象的值是 go web
        if err != nil{
            fmt.Fprintf(writer,"Execute:%v",err)
            return
        }
    })
    log.Println("Starting Server....")
    log.Fatal(http.ListenAndServe(":4000",nil))
}
go run test.go 输出:
2018/07/10 11:10:01 Starting Server....

浏览器访问:http://localhost:4000/
Go编程基础5-基础模板用法_第5张图片

6、创建一个真正的html页面

vim main.html


    Go Web

    
    

Package info:

  • Package name: {{.Name}}}
  • Number of functions:{{.NumFuncs}}}
  • Number of variables: {{.NumVars}}}
  • package main import( "html/template" "log" "net/http" "fmt" ) type Package struct { Name string NumFuncs int NumVars int } func main(){ http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { tmpl,err := template.ParseFiles("main.html") if err != nil { fmt.Fprintf(writer,"ParseFiles:%v",err) return } err = tmpl.Execute(writer,&Package{ Name :"go-web", NumFuncs:14, NumVars:1200, }) if err != nil{ fmt.Fprintf(writer,"Execute:%v",err) return } }) log.Println("Starting Server....") log.Fatal(http.ListenAndServe(":4000",nil)) } go run test.go 输出: 2018/07/10 11:24:51 Starting Server....

    浏览器访问:http://localhost:4000/
    Go编程基础5-基础模板用法_第6张图片
    右键查看网页源代码:view-source:http://localhost:4000/

    
    
        Go Web
    
        
        

    Package info:

  • Package name: go-web}
  • Number of functions:14}
  • Number of variables: 1200}
  • 7、简单应用,根据成绩判断成绩等级是A,B,C.....

    首先完成从请求参数中获取成绩score的大小
    vim main.html
    
    
        Go Web
    
        
            {{.}}
        
    
    
    package main
    import(
        "html/template"
        "log"
        "net/http"
        "fmt"
    )
    type Package struct {
        Name string
        NumFuncs int
        NumVars int
    }
    func main(){
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            tmpl,err := template.ParseFiles("main.html")
            if err != nil {
                fmt.Fprintf(writer,"ParseFiles:%v",err)
                return
            }
            score := request.FormValue("score")
            err = tmpl.Execute(writer,score)
            if err != nil{
                fmt.Fprintf(writer,"Execute:%v",err)
                return
            }
        })
        log.Println("Starting Server....")
        log.Fatal(http.ListenAndServe(":4000",nil))
    }
    go run test.go 输出:
    2018/07/10 11:33:01 Starting Server....

    访问:http://localhost:4000/?score=100
    输出100
    访问:http://localhost:4000/?score=1
    输出1
    符合预期

    判断score是否存在

    vim main.html
    
    
        Go Web
    
        
            {{if .}}
                    score is {{.}}
            {{else}}
                    no score
            {{end}}
        
    
    
    vim test.go
    package main
    import(
    "html/template"
    "log"
    "net/http"
    "fmt"
    )
    type Package struct {
        Name string
        NumFuncs int
        NumVars int
    }
    func main(){
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            tmpl,err := template.ParseFiles("main.html")
            if err != nil {
                fmt.Fprintf(writer,"ParseFiles:%v",err)
                return
            }
            score := request.FormValue("score")
            err = tmpl.Execute(writer,score)
            if err != nil{
                fmt.Fprintf(writer,"Execute:%v",err)
                return
            }
        })
        log.Println("Starting Server....")
        log.Fatal(http.ListenAndServe(":4000",nil))
    }
    go run test.go 输出:
    2018/07/10 11:38:10 Starting Server....

    访问:http://localhost:4000/?score=100
    Go编程基础5-基础模板用法_第7张图片
    访问:http://localhost:4000/
    Go编程基础5-基础模板用法_第8张图片

    对数值进行比较

    vim main.html
    
    
        Go Web
    
        
            {{if gt . 90}}
                    A
            {{else if gt . 80}}
                    B
            {{else if gt . 70}}
                    C
            {{else if gt . 60}}
                    D
            {{else}}
                    F
            {{end}}
        
    
    报错:Execute:template: main.html:6:13: executing "main.html" at : error calling gt: incompatible types for comparison
    原因是request.FormValue("score")返回的是string类型,不能与int型90比较
    修改返回类型
    vim test.go
    package main
    import(
    "html/template"
    "log"
    "net/http"
    "fmt"
    "strconv"
    )
    type Package struct {
        Name string
        NumFuncs int
        NumVars int
    }
    func main(){
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            tmpl,err := template.ParseFiles("main.html")
            if err != nil {
                fmt.Fprintf(writer,"ParseFiles:%v",err)
                return
            }
            score := request.FormValue("score")
            num, _ := strconv.Atoi(score)
            err = tmpl.Execute(writer,num)
            if err != nil{
                fmt.Fprintf(writer,"Execute:%v",err)
                return
            }
        })
        log.Println("Starting Server....")
        log.Fatal(http.ListenAndServe(":4000",nil))
    }
    go run test.go 输出:
    2018/07/10 11:53:59 Starting Server....

    访问:http://localhost:4000/?score=100 输出A
    Go编程基础5-基础模板用法_第9张图片
    http://localhost:4000/?score=80 输出C
    http://localhost:4000/?score=60 输出F

    8、range改变作用域

    vim main.html
    
    
        Go Web
    
        
            {{range $key,$value := .Header}}
            

    Method: {{$.Method}} key: {{$key}}

    {{range $value}}

  • {{.}}
  • {{end}}

    {{end}} vim test.go package main import( "html/template" "log" "net/http" "fmt" ) type Package struct { Name string NumFuncs int NumVars int } func main(){ http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { tmpl,err := template.ParseFiles("main.html") if err != nil { fmt.Fprintf(writer,"ParseFiles:%v",err) return } err = tmpl.Execute(writer,request) if err != nil{ fmt.Fprintf(writer,"Execute:%v",err) return } }) log.Println("Starting Server....") log.Fatal(http.ListenAndServe(":4000",nil)) } go run test.go 输出: 2018/07/10 12:14:13 Starting Server....

    http://localhost:4000/
    Go编程基础5-基础模板用法_第10张图片

    9、with改变作用域

    
        
            Go Web
        
        
            {{with .URL}}
                {{.}}
                {{.Scheme}}
                {{.User}}
                {{.Host}}
                {{.Path}}
                {{end}}
        
    
    
    package main
    import(
    "html/template"
    "log"
    "net/http"
    "fmt"
    )
    type Package struct {
        Name string
        NumFuncs int
        NumVars int
    }
    func main(){
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            tmpl,err := template.ParseFiles("main.html")
            if err != nil {
                fmt.Fprintf(writer,"ParseFiles:%v",err)
                return
            }
            err = tmpl.Execute(writer,request)
            if err != nil{
                fmt.Fprintf(writer,"Execute:%v",err)
                return
            }
        })
        log.Println("Starting Server....")
        log.Fatal(http.ListenAndServe(":4000",nil))
    }
    go run test.go 输出:

    访问:http://localhost:4000/1234?score=80 输出:
    /1234?score=80 /1234

    10、with改变作用域

    web中想临时输出一些字符串,字段,怎么办?
    维护一个大的结构不方便
    将跟对象变成一个key类型为string,值类型为空接口的map,再在map中放入需要传入的所有对象,除此之外,还有一个好处,就是可以把map申明为一个变量,在不同的 Handler中进行传递,在最后响应的这个Handler之前,不断的将map中添加新的内容,最终模板渲染的时候,就可以使用到所有的内容

    
        
            Go Web
        
        
            {{.Request}}
            {{.Score}}
        
    
    
    package main
    import(
    "html/template"
    "log"
    "net/http"
    "fmt"
    )
    type Package struct {
        Name string
        NumFuncs int
        NumVars int
    }
    func main(){
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            tmpl,err := template.ParseFiles("main.html")
            if err != nil {
                fmt.Fprintf(writer,"ParseFiles:%v",err)
                return
            }
            err = tmpl.Execute(writer,map[string]interface{}{
                "Request": request,
                "Score": 97,
            })
            if err != nil{
                fmt.Fprintf(writer,"Execute:%v",err)
                return
            }
        })
        log.Println("Starting Server....")
        log.Fatal(http.ListenAndServe(":4000",nil))
    }
    go run test.go 输出:
    2018/07/10 12:29:10 Starting Server....

    http://localhost:4000/ 输出score=97 和GET方法
    Go编程基础5-基础模板用法_第11张图片