1 package main 2 3 import ( 4 "html/template" 5 "math/rand" 6 "net/http" 7 "time" 8 ) 9 10 func process(w http.ResponseWriter, r *http.Request) { 11 t := template.Must(template.ParseFiles("tmpl.html")) //解析制定文件 生成模板对象 12 /* 13 rand.Intn () 函数是个伪随机函数,不管运行多少次都只会返回同样的随机数,因为它默认的资源就是单一值, 14 所以必须调用 rand.Seed (), 并且传入一个变化的值作为参数,如 time.Now().UnixNano() , 就是可以生成时刻变化的值. 15 */ 16 rand.Seed(time.Now().Unix()) 17 t.Execute(w, rand.Intn(10) > 5) //返回为bool值 18 19 //t.Execute(w,"hello world") //利用数据进行渲染 写入w 20 //如果是模板集合则调用下面的方法对指定模板进行渲染 21 //t.ExecuteTemplate(w,"tmpl.html","helloworld") 22 } 23 24 //迭代 25 func tmplRange(w http.ResponseWriter, r *http.Request) { 26 t := template.Must(template.ParseFiles("tmplrange.html")) //解析制定文件 生成模板对象 27 //创建字符串数组 28 dayofWeek := []string{"mon", "tue", "wen", "thu", "fri", "sat", "sun"} 29 //写入结果 30 t.Execute(w, dayofWeek) 31 } 32 33 //函数 34 func formatData(t time.Time) string { 35 layout := "2006-01-02" 36 return t.Format(layout) 37 } 38 39 func tmplfunc(w http.ResponseWriter, r *http.Request) { 40 //创建一个funcmap的映射 将fdata映射到函数formatData 41 funcMap := template.FuncMap{"fdata": formatData} 42 //创建一个模板 并将前边的函数映射给模板 43 t := template.New("tmplfunc.html").Funcs(funcMap) 44 //解析模板 45 t, _ = t.ParseFiles("tmplfunc.html") 46 //返回结果 47 t.Execute(w, time.Now()) 48 } 49 50 //模板嵌套 51 func tmplNested(w http.ResponseWriter,r *http.Request){ 52 t,_:=template.ParseFiles("tmpllayout.html","tmplcontent.html") 53 t.Execute(w,"") 54 } 55 56 func main() { 57 http.HandleFunc("/process", process) 58 http.HandleFunc("/range", tmplRange) 59 http.HandleFunc("/func", tmplfunc) 60 http.HandleFunc("/nested",tmplNested) 61 http.ListenAndServe(":8080", nil) 62 63 }
//迭代 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>======================================</h1> 9 {{ range .}} 10 <li> {{ .}}</li> 11 {{ end}} 12 <h1>可以将一个参数传递给另一个参数 中间用|隔开</h1> 13 {{ 12.3456 | printf "%.2f"}} 14 </body> 15 </html>
//模板函数 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>func</title> 6 </head> 7 <body> 8 当前的时间为:{{ . | fdata}} 9 </body> 10 </html>
//模板嵌套 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>Hello world!</h1> 9 </body> 10 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {{ template "tmplcontent.html"}} 9 {{ template "ol.html"}} 10 </body> 11 </html> 12 13 {{ define "ol.html"}} 14 <ol> 15 <li>吃饭</li> 16 <li>睡觉</li> 17 <li>打豆豆</li> 18 </ol> 19 {{ end}}
来源:https://www.cnblogs.com/yh2924/p/12602907.html