Golang 模板基础语法范例

前端之家收集整理的这篇文章主要介绍了Golang 模板基础语法范例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
匿名对象字段值

package main

import (
"html/template"
"os"
"time"
)

func main() {
stus := struct {
Name string
Birth time.Time
Age int
}{
Name: "Swallow",Birth: time.Unix(534182400,0),Age: 30,
}

t := template.Must(template.New("testing").Parse(`{{.Birth}} *** {{.Age}}`))
t.Execute(os.Stdout,stus)
}



Map ------ 在template中key没有空格

package main

import (
"html/template"
"os"
)

func main() {
data := map[string]bool{
"Jack": true,
"Jason": false,
"Jim": false,
}
t := template.Must(template.New("testing").Parse(`Married: Jack:{{ .Jack}}; Jim:{{ .Jim}}`))
t.Execute(os.Stdout,data)
}






Map ------ 在template中key有空格,必须用index

package main

import (
"html/template"
"os"
)

func main() {
data := map[string]bool{
"Jack Chen": true,
"YangFan": false,
}
t := template.Must(template.New("testing").Parse(`Married: Jack Chen:{{index . "Jack Chen"}}; YangFan:{{ .YangFan}}`))
t.Execute(os.Stdout,data)
}



数组/切片

import (
"html/template"
"os"
)

func main() {
data := []string{"Jack Chen","YangFan","Tim","Jason","Tina"}
t := template.Must(template.New("test").Parse("Teacher List:" + "{{range .}}" + "\n{{.}};" + "{{end}}"))
t.Execute(os.Stdout,data)
}


自定义变量

package main

import (
"html/template"
"os"
)

func main() {
data := []string{"Jack Chen","Tina"}
t := template.Must(template.New("test").Parse("Students List:" + "{{range $index,$_ := .}}" + "\n{{$index}}). {{.}}," + "{{end}}"))
t.Execute(os.Stdout,data)
}


条件查询
package main

import (
"html/template"
"os"
)

func main() {
//p := "Jack Chen"
p := "Tina"
t := template.Must(template.New("test").Parse(`{{if eq . "Jack Chen"}} Jack Chen is Man {{else if eq . "Tina"}} Tina is Woman {{end}}`))
t.Execute(os.Stdout,p)
}



转义

package main

import (
"html/template"
"os"
)

func main() {
//p := "Jack Chen"
p := "Tina"
t := template.Must(template.New("test").Parse(`<a href="/search?name={{.}}">{{.}}</a>`))
t.Execute(os.Stdout,p)
}

转义

package main

import (
"html/template"
"os"
)

func main() {
p := "Jack Chen"
//p := "Tina"
t := template.Must(template.New("test").Parse(`<a href="/search?name={{. | urlquery}}">{{. | html}}</a>`))
t.Execute(os.Stdout,p)
}

转义

package main

import (
"html/template"
"os"
)

func main() {
js := "<script>"
t := template.Must(template.New("test").Parse("{{. | urlquery}} and {{. | html}}"))
t.Execute(os.Stdout,js)
}

模板重构 ------ 自定义方法

package main

import (
"html/template"
"os"
)

func IsBoolean(b bool) bool {
return b
}

func main() {
funcs := template.FuncMap{
"status": func(b bool) bool { return b },
}
t := template.New("test").Funcs(funcs)
template.Must(t.Parse("{{if status .}} Go Code is running! {{ else }} Go Code is running appear panic! {{end}}"))
t.Execute(os.Stdout,false)
}


模板重构 ------ 嵌套模板


package main

import (
"html/template"
"os"
)

type Student struct {
Name string
Age int
}

func main() {
s := &Student{Name: "Jack Chen",Age: 30}
t := template.New("test")
// parent template
template.Must(t.Parse(`Name: {{.Name}} is from parent; {{template "age" .Age}} is from child`))
// child template
template.Must(t.Parse(`{{define "age"}}Age: {{.}}{{end}}`))
t.Execute(os.Stdout,s)
}


Session接口对象如何输出到 Golang的Template中:

/root/code/go/src/contoso.org/hello/main.go

package main

import (
"crypto/md5"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"time"

"github.com/astaxie/beego/session"
)

var globalSessions *session.Manager

func init() {
config := `{"cookieName":"gosessionid","gclifetime":3600,"enableSetCookie":true}`
conf := new(session.ManagerConfig)
if err := json.Unmarshal([]byte(config),conf); err != nil {
log.Fatal("json decode error",err)
}
globalSessions,_ = session.NewManager("memory",conf)
go globalSessions.GC()
}

func main() {
http.HandleFunc("/count",count) //设置访问的路由
err := http.ListenAndServe(":9090",nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ",err)
}
}

//网站访问计数器
func count(w http.ResponseWriter,r *http.Request) {
fmt.Println("Requesting Addr 2: ",r.URL.Path)
//忽略此路由地址请求:http://127.0.0.1:9090/favicon.ico
if r.URL.Path != "/favicon.ico" {
sess,_ := globalSessions.SessionStart(w,r)
ct := sess.Get("countnum")
if ct == nil {
sess.Set("countnum",1)
fmt.Println("Count SessionID = ",sess.SessionID())
} else {
sess.Set("countnum",(ct.(int) + 1))
fmt.Println("Count SessionID = ",sess.SessionID())
}
t,_ := template.ParseFiles("count.gtpl")
w.Header().Set("Content-Type","text/html")
fmt.Println("\n ****** Request Header: ******")
for k,v := range r.Header {
fmt.Println(k," = ",v) //v是[]string,输出值带有中括号
}
fmt.Println("\n ****** Response Header: ******")
for k,v := range w.Header() {
fmt.Println(k,输出值带有中括号
}
fmt.Println(" ======================================================================= ")

h := md5.New()
salt := "lengrubing%^7&8888"
io.WriteString(h,salt+time.Now().String())
token := fmt.Sprintf("%x",h.Sum(nil))
if r.Form.Get("token") != token {
//提示登录
}
sess.Set("token",token)
//自定义一个匿名对象data,sess.Get返回的是个接口,必须指明该返回值的类型,
//注意匿名对象初始化时,每行必须,是必须要有一个逗号

data := struct {
Token string
Count int
}{
sess.Get("token").(string),
sess.Get("countnum").(int),
}
t.Execute(w,data)

}
}


/root/code/go/src/contoso.org/hello/count.gtpl

<!DOCTYPE html>
<html>
<head>
<title>计数器 - 以及Session接口对象如何输出到模板内对应的标签中</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
</head>
<body>
<div>
Token:<input type="text" name="token" value={{.Token}}><br>
Count:<input type="text" name="count" value={{.Count}}><br>

自定义匿名对象:{{.}}
</dev>
</body>
</html>


更多范例正在更新中 。。。。。。

原文链接:https://www.f2er.com/go/188333.html

猜你在找的Go相关文章