這篇文章給大家分享的是有關(guān)Go Web編程中的模板庫有什么用的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)科技有限公司專業(yè)互聯(lián)網(wǎng)基礎(chǔ)服務(wù)商,為您提供移動服務(wù)器托管,高防服務(wù)器租用,成都IDC機(jī)房托管,成都主機(jī)托管等互聯(lián)網(wǎng)服務(wù)。
如果你有過Web編程的經(jīng)驗(yàn),那么或多或少都聽說過或者使用過模板。簡而言之,模板是可用于創(chuàng)建動態(tài)內(nèi)容的文本文件。例如,你有一個網(wǎng)站導(dǎo)航欄的模板,其中動態(tài)內(nèi)容的一部分可能是根據(jù)當(dāng)前用戶是否登錄顯示登錄還是退出按鈕。
Go提供了兩個模板庫 text/template和 html/template。這兩個模板庫的使用方式是相同的,但是 html/template包在渲染頁面模板時會在后臺進(jìn)行一些編碼以幫助防止造成代碼注入(XSS 攻擊)。
因?yàn)閮蓚€模板庫都使用相同的接口,因此本文中介紹的所有內(nèi)容均可用于這兩個程序包,但是大多數(shù)時候我們都會使用 html/template程序包來生成HTML代碼段。
模板文件的后綴名
模板文件可以使用 .html或任何其他擴(kuò)展名。但是通常我們將使用 .gohtml擴(kuò)展名來命名模板文件,因?yàn)榫庉嬈魍ǔJ褂盟鼇肀硎灸阆胍吡?GoHTML模板語法。Atom和 SublimeText等編輯器都具有 Go插件,來默認(rèn)識別此擴(kuò)展名。
模板語法
我們先來創(chuàng)建一個簡單的模板文件 test.gohtml:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Go Web</title> </head> <body> {{ . }} </body> </html>
{{ 和 }} 中間的半角句號 . 它代表模板對象執(zhí)行 Execute(w,data)傳入模板的數(shù)據(jù),它是頂級作用域范圍內(nèi)的,根據(jù)傳入的數(shù)據(jù)不同渲染不同的內(nèi)容。. 可以代表 Go語言中的任何類型,如結(jié)構(gòu)體、 Map等。
在寫模板的時候,會經(jīng)常用到 .。比如 {{.}}、 {{len.}}、 {{.Name}}、 {{$x.Name}}
{{ 和 }} 包裹的內(nèi)容統(tǒng)稱為 action,分為兩種類型:
數(shù)據(jù)求值(data evaluations)
控制結(jié)構(gòu)(control structures)
action求值的結(jié)果會直接復(fù)制到模板中,控制結(jié)構(gòu)和我們寫 Go程序差不多,也是條件語句、循環(huán)語句、變量、函數(shù)調(diào)用等等...模板中的 action 并不多,我們一個一個看。
注釋
{{/* comment */}}
裁剪空字符
注意裁剪的是替換內(nèi)容前面或者后面的空字符,你可以理解成模板中{{前面或}}后面的空字符(包括換行符、制表符、空格等)。
// 裁剪 content 前后的空字符
{{- content -}}
// 裁剪 content 前面的空字符
{{- content }}
// 裁剪 content 后面的空字符
{{ content -}}
文本輸出
{{ pipeline }}
pipeline代表的數(shù)據(jù)會產(chǎn)生與調(diào)用 fmt.Print 函數(shù)類似的輸出,例如整數(shù)類型的 3 會轉(zhuǎn)換成字符串 "3" 輸出。
條件語句
{{ if pipeline }} T1 {{ end }}
{{ if pipeline }} T1 {{ else }} T0 {{ end }}
{{ if pipeline }} T1 {{ else if pipeline }} T0 {{ end }}
// 上面的語法其實(shí)是下面的簡寫
{{ if pipeline }} T1 {{ else }}{{ if pipeline }} T0 { {end }}{{ end }}
{{ if pipeline }} T1 {{ else if pipeline }} T2 {{ else }} T0 {{ end }}
如果 pipeline 的值為空,不會輸出 T1,除此之外 T1 都會被輸出。
空值有 false、 0、 nil空字符串 ""(長度為 0 的字符串)。
循環(huán)語句
{{ range pipeline }} T1 {{ end }}
// 這個 else 比較有意思,如果 pipeline 的長度為 0 則輸出 else 中的內(nèi)容
{{ range pipeline }} T1 {{ else }} T0 {{ end }}
// 獲取容器的下標(biāo)
{{ range $index, $value := pipeline }} T1 {{ end }}
循環(huán)語句中的 pipeline 的值必須是數(shù)組、切片、字典和通道中的一種,即可迭代類型的值,根據(jù)值的長度輸出多個 T1。
define
{{ define "name" }} T {{ end }}
定義命名為 name 的模板。
template
{{ template "name" }}
{{ template "name" pipeline }}
第一種是直接執(zhí)行名為 name的模板,模板的全局?jǐn)?shù)據(jù)對象 .設(shè)置為 nil。第二種是點(diǎn) .設(shè)置為pipeline的值,并執(zhí)行名為 name的模板。
block
{{ block "name" pipeline }} T1 {{ end }}
block 的語義是如果有命名為 name 的模板,就引用過來執(zhí)行,如果沒有命名為 name 的模板,就是執(zhí)行自己定義的內(nèi)容。換句話說,block可以認(rèn)為是設(shè)置一個默認(rèn)模板。
with
{{ with pipeline }} T1 {{ end }}
// 如果 pipeline 是空值則輸出 T0
{{ with pipeline }} T1 {{ else }} T0 {{ end }}
{{ with arg }}
. // 此時 . 就是 arg
{{ end }}
with 創(chuàng)建一個新的上下文環(huán)境,在此環(huán)境中的 . 與外面的 . 無關(guān)。
對于第一種格式,當(dāng)pipeline不為0值的時候,點(diǎn) .設(shè)置為pipeline運(yùn)算的值,否則跳過。對于第二種格式,當(dāng)pipeline為0值時,執(zhí)行else語句塊,否則 .設(shè)置為pipeline運(yùn)算的值,并執(zhí)行T1。
例如:
{{with .Person}}{{ .Name}}{{end}}
在這個 with 塊中 .Name實(shí)際上引用的是全局?jǐn)?shù)據(jù)對象的 .Person.Name。
實(shí)踐練習(xí):課程花名冊頁面
了解完模板語法后,接下來讓我們在 http_demo項(xiàng)目中結(jié)合 BootStrap創(chuàng)建一個簡單的模板,來展示服務(wù)器如何把數(shù)據(jù)傳遞給模板、渲染 HTML頁面,把頁面響應(yīng)返回給客戶端。
我們創(chuàng)建一個用來展示大學(xué)物理課程的花名冊(授課老師和上課學(xué)生)
創(chuàng)建頁面模板
首先在我們的項(xiàng)目添加一個 views目錄用于存放模板文件,在創(chuàng)建三個模板文件分別是:
layout.gohtml 用于存放頁面的整體布局。
<html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Bootstrap Template Page for Go Web Programming</title> <!-- Bootstrap core CSS --> <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> </head> <body> {{ template "nav" .}} <div class="container"> {{template "content" .}} </div> <script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>
nav.gohtml是網(wǎng)頁頭部區(qū)域的頁面模板。
{{define "nav"}} <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Person general infor</a> </div> </div> </nav> <div class="jumbotron"> <div class="container"> <h2>Hello, Professor {{.Teacher.Name}}</h2> <ul> <li>Name : {{.Teacher.Name}}<p> <li>Subject : {{.Teacher.Subject}} </ul> <p><a class="btn btn-primary btn-lg" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" role="button">More »</a></p> </div> </div> {{end}}
content.gohtml是網(wǎng)頁主體內(nèi)容部分的頁面模板。
{{define "content"}} {{range .Students}} <div class="row"> <div class="col-md-4"> <h3>Name</h3> <p>Name has the value of : {{.Name}} </p> <p><a class="btn btn-default" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" role="button">More »</a></p> </div> <div class="col-md-4"> <h3>Id</h3> <p>Id has the value of : {{.Id}} </p> <p><a class="btn btn-default" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" role="button">More »</a></p> </div> <div class="col-md-4"> <h3>Country</h3> <p>Country has the value of : {{.Country}} </p> <p><a class="btn btn-default" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" role="button">More »</a></p> </div> </div> {{end}} {{end}}
在 layout.gohtml中我們引用了另外的兩個模板:
{{ template "nav" .}}
{{template "content" .}}
這樣不同的頁面變化的部分就只是 content部分,針對不同的頁面我們只需要定義多個 content模板,每次根據(jù)不同請求使用不同的 content模板就行了。當(dāng)然這里的例子有點(diǎn)簡陋,大家理解意思就行了。
注意模板名稱后面的 .,我們把 layout.gohtml的全局?jǐn)?shù)據(jù)對象傳給了另外兩個模板這樣,在子模板里也能訪問傳給模板的數(shù)據(jù)了。如果頁面模板中使用的數(shù)據(jù)字段和循環(huán)語句有點(diǎn)疑惑可以先不用管,繼續(xù)往下看,等看過傳給頁面模板的數(shù)據(jù)后自然就理解了。
創(chuàng)建響應(yīng)頁面請求的Handler
接下來創(chuàng)建一個伺服頁面請求的 Handler:
package handler import ( "fmt" "html/template" "net/http" ) type Teacher struct { Name string Subject string } type Student struct { Id int Name string Country string } type Rooster struct { Teacher Teacher Students []Student } func ShowIndexView(response http.ResponseWriter, request *http.Request) { teacher := Teacher{ Name: "Alex", Subject: "Physics", } students := []Student{ {Id: 1001, Name: "Peter", Country: "China"}, {Id: 1002, Name: "Jeniffer", Country: "Sweden"}, } rooster := Rooster{ Teacher: teacher, Students: students, } tmpl, err := template.ParseFiles("./views/layout.gohtml", "./views/nav.gohtml", "./views/content.gohtml") if err != nil { fmt.Println("Error " + err.Error()) } tmpl.Execute(response, rooster) }
使用 template.ParseFiles加載這個頁面要使用的全部三個模板(如果加載少了,訪問頁面時會發(fā)生 panic),然后使用模板對象的 Execute方法把我們存儲了花名冊信息的數(shù)據(jù)對象傳給模板: tmpl.Execute(response,rooster) 渲染頁面并寫到響應(yīng)里去( http.ResponseWriter對象)。
注冊頁面路由
處理程序?qū)懲旰螅瑸槠渥月酚?,在我們?xiàng)目的路由模塊添加如下路由:
package router import ( "example.com/http_demo/middleware" "github.com/gorilla/mux" "example.com/http_demo/handler" ) func RegisterRoutes(r *mux.Router) { r.Use(middleware.Logging()) ... viewRouter := r.PathPrefix("/view").Subrouter() viewRouter.HandleFunc("/index", handler.ShowIndexView) }
訪問頁面
現(xiàn)在所有步驟都完成了,重啟我們的服務(wù)器后就可以訪問到新寫的頁面了。
如果是在本地電腦里,用 Ctrl+C結(jié)束服務(wù)器進(jìn)程后再次執(zhí)行 go run main.go
。如果是使用我們之前文章里的 Docker開發(fā)環(huán)境的話,需要在 docker-compose.yml
所在的目錄里用 docker-compose restart
重啟服務(wù)。
打開瀏覽器輸入 http://localhost:8000/view/index就能訪問到我們剛才寫的頁面了。
感謝各位的閱讀!關(guān)于“Go Web編程中的模板庫有什么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
文章題目:GoWeb編程中的模板庫有什么用
URL地址:http://aaarwkj.com/article30/jescso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、營銷型網(wǎng)站建設(shè)、電子商務(wù)、企業(yè)建站、標(biāo)簽優(yōu)化、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)