博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go编程基础5-基础模板用法
阅读量:6261 次
发布时间:2019-06-22

本文共 13090 字,大约阅读时间需要 43 分钟。

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

package mainimport(    "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 mainimport(    "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 webpackage mainimport( "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 mainimport( "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 mainimport(    "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....

浏览器访问:

Go编程基础5-基础模板用法

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

package mainimport(    "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.tmplPackage name: {
{.Name}}Number of functions: {
{.NumFuncs}}Number of variables: {
{.NumVars}}go run test.go 输出:2018/07/10 10:52:56 Starting Server....

浏览器访问:

Go编程基础5-基础模板用法

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

➜  test vim main.tmplMethod: {
{.Method}}package mainimport( "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....

浏览器访问: 打印出了Method:GET

Go编程基础5-基础模板用法

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

浏览器访问: 打印出Path: /

Go编程基础5-基础模板用法

打印User-Agent

修改main.tmplMethod: {
{.Method}}Path: {
{.URL.Path}}Header: {
{.Header.Get "User-Agent"}}package mainimport( "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....

浏览器访问:

Go编程基础5-基础模板用法

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

vim main.html    Go Web        

Package info:

  • Package name: {
    {.Name}}}
  • Number of functions:{
    {.NumFuncs}}}
  • Number of variables: {
    {.NumVars}}}
  • package mainimport( "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....

    浏览器访问:

    Go编程基础5-基础模板用法
    右键查看网页源代码:view-source:

        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 mainimport( "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....

    访问:

    输出100
    访问:
    输出1
    符合预期

    判断score是否存在

    vim main.html    Go Web            {
    {if .}} score is {
    {.}} {
    {else}} no score {
    {end}} vim test.gopackage mainimport("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....

    访问:

    Go编程基础5-基础模板用法
    访问:
    Go编程基础5-基础模板用法

    对数值进行比较

    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.gopackage mainimport("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....

    访问: 输出A

    Go编程基础5-基础模板用法
    输出C
    输出F

    8、range改变作用域

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

    Method: {

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

    {

    {range $value}}

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

    {
    {end}} vim test.gopackage mainimport("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....

    Go编程基础5-基础模板用法

    9、with改变作用域

                Go Web                {
    {with .URL}} {
    {.}} {
    {.Scheme}} {
    {.User}} {
    {.Host}} {
    {.Path}} {
    {end}} package mainimport("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 输出:

    访问: 输出:

    /1234?score=80 <nil> /1234

    10、with改变作用域

    web中想临时输出一些字符串,字段,怎么办?

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

                Go Web                {
    {.Request}} {
    {.Score}} package mainimport("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....

    输出score=97 和GET方法

    Go编程基础5-基础模板用法

    转载于:https://blog.51cto.com/daixuan/2139701

    你可能感兴趣的文章
    PHP 如何显示大数字,防止显示为 科学计数法 形式
    查看>>
    数据扩展性探讨和总结--转
    查看>>
    spider RPC高级特性
    查看>>
    C# 导出资源文件到硬盘
    查看>>
    修复 ThinkPHP3.2.3 抛出异常模块的一个BUG,关闭字段缓存功能
    查看>>
    更改MySQL数据库的编码为utf8mb4
    查看>>
    android自动化测试--appium运行的坑问题及解决方法
    查看>>
    mysql Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’
    查看>>
    TeamCity : .NET Core 插件
    查看>>
    Python 爬虫知识点 - XPath
    查看>>
    由数量众多照片拼贴而成的马赛克图片
    查看>>
    如何在linux Shell脚本里面把一个数组传递到awk内部进行处理
    查看>>
    共模电感的原理以及使用情况
    查看>>
    GridLookUpEdit多列模糊查询最简单方式 z
    查看>>
    memcache与Redis
    查看>>
    Python27中Json对中文的处理
    查看>>
    结构,是指事物自身各种要素之间的相互关联和相互作用的方式
    查看>>
    andoid电阻触摸移植
    查看>>
    备忘录模式
    查看>>
    U盘安装CentOS 7卡住在 mounting configuration file system
    查看>>