摘要:從模板文件構(gòu)建首頁(yè)新聞手動(dòng)的指定每一個(gè)模板文件,在一些場(chǎng)景下難免難以滿足需求,我們可以使用通配符正則匹配載入。
從字符串載入模板
我們可以定義模板字符串,然后載入并解析渲染:
template.New(tplName string).Parse(tpl string)
// 從字符串模板構(gòu)建 tplStr := ` {{ .Name }} {{ .Age }} ` // if parse failed Must will render a panic error tpl := template.Must(template.New("tplName").Parse(tplStr)) tpl.Execute(os.Stdout, map[string]interface{}{Name: "big_cat", Age: 29})從文件載入模板 模板語(yǔ)法
模板文件,建議為每個(gè)模板文件顯式的定義模板名稱:{{ define "tplName" }},否則會(huì)因模板對(duì)象名與模板名不一致,無(wú)法解析(條件分支很多,不如按一種標(biāo)準(zhǔn)寫法實(shí)現(xiàn)),另展示一些基本的模板語(yǔ)法。
使用 {{ define "tplName" }} 定義模板名
使用 {{ template "tplName" . }}引入其他模板
使用 . 訪問(wèn)當(dāng)前數(shù)據(jù)域:比如range里使用.訪問(wèn)的其實(shí)是循環(huán)項(xiàng)的數(shù)據(jù)域
使用 $. 訪問(wèn)絕對(duì)頂層數(shù)據(jù)域
views/header.html{{ define "header" }}views/footer.html{{ .PageTitle }} {{ end }}
{{ define "footer" }} {{ end }}views/index/index.html
{{ define "index/index" }} {{/*引用其他模板 注意后面的 . */}} {{ template "header" . }}views/news/index.htmlhello, {{ .Name }}, age {{ .Age }}{{ template "footer" . }} {{ end }}
{{ define "news/index" }} {{ template "header" . }} {{/* 頁(yè)面變量定義 */}} {{ $pageTitle := "news title" }} {{ $pageTitleLen := len $pageTitle }} {{/* 長(zhǎng)度 > 4 才輸出 eq ne gt lt ge le */}} {{ if gt $pageTitleLen 4 }}template.ParseFiles{{ $pageTitle }}
{{ end }} {{ $c1 := gt 4 3}} {{ $c2 := lt 2 3 }} {{/*and or not 條件必須為標(biāo)量值 不能是邏輯表達(dá)式 如果需要邏輯表達(dá)式請(qǐng)先求值*/}} {{ if and $c1 $c2 }}1 == 1 3 > 2 4 < 5
{{ end }}{{ template "footer" . }} {{ end }}{{ range .List }} {{ $title := .Title }} {{/* .Title 上下文變量調(diào)用 func param1 param2 方法/函數(shù)調(diào)用 $.根節(jié)點(diǎn)變量調(diào)用 */}}
{{/* !empty Total 才輸出*/}} {{ with .Total }}- {{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}
{{end}}總數(shù):{{ . }}{{ end }}
手動(dòng)定義需要載入的模板文件,解析后制定需要渲染的模板名news/index。
// 從模板文件構(gòu)建 tpl := template.Must( template.ParseFiles( "views/index/index.html", "views/news/index.html", "views/header.html", "views/footer.html", ), ) // render template with tplName index _ = tpl.ExecuteTemplate( os.Stdout, "index/index", map[string]interface{}{ PageTitle: "首頁(yè)", Name: "big_cat", Age: 29, }, ) // render template with tplName index _ = tpl.ExecuteTemplate( os.Stdout, "news/index", map[string]interface{}{ "PageTitle": "新聞", "List": []struct { Title string CreatedAt time.Time }{ {Title: "this is golang views/template example", CreatedAt: time.Now()}, {Title: "to be honest, i don"t very like this raw engine", CreatedAt: time.Now()}, }, "Total": 1, "Author": "big_cat", }, )template.ParseGlob
手動(dòng)的指定每一個(gè)模板文件,在一些場(chǎng)景下難免難以滿足需求,我們可以使用通配符正則匹配載入。
1、正則不應(yīng)包含文件夾,否則會(huì)因文件夾被作為視圖載入無(wú)法解析而報(bào)錯(cuò)
2、可以設(shè)定多個(gè)模式串,如下我們載入了一級(jí)目錄和二級(jí)目錄的視圖文件
// 從模板文件構(gòu)建 tpl := template.Must(template.ParseGlob("views/*.html")) template.Must(tpl.ParseGlob("views/*/*.html")) // render template with tplName index // render template with tplName index _ = tpl.ExecuteTemplate( os.Stdout, "index/index", map[string]interface{}{ PageTitle: "首頁(yè)", Name: "big_cat", Age: 29, }, ) // render template with tplName index _ = tpl.ExecuteTemplate( os.Stdout, "news/index", map[string]interface{}{ "PageTitle": "新聞", "List": []struct { Title string CreatedAt time.Time }{ {Title: "this is golang views/template example", CreatedAt: time.Now()}, {Title: "to be honest, i don"t very like this raw engine", CreatedAt: time.Now()}, }, "Total": 1, "Author": "big_cat", }, )Web服務(wù)器
結(jié)合html/template模板庫(kù)和net/http實(shí)現(xiàn)一個(gè)可以使用模板渲染并返回html頁(yè)面的web服器。
package main import ( "html/template" "log" "net/http" "time" ) var ( htmlTplEngine *template.Template htmlTplEngineErr error ) func init() { // 初始化模板引擎 并加載各層級(jí)的模板文件 // 注意 views/* 不會(huì)對(duì)子目錄遞歸處理 且會(huì)將子目錄匹配 作為模板處理造成解析錯(cuò)誤 // 若存在與模板文件同級(jí)的子目錄時(shí) 應(yīng)指定模板文件擴(kuò)展名來(lái)防止目錄被作為模板文件處理 // 然后通過(guò) view/*/*.html 來(lái)加載 view 下的各子目錄中的模板文件 htmlTplEngine = template.New("htmlTplEngine") // 模板根目錄下的模板文件 一些公共文件 _, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*.html") if nil != htmlTplEngineErr { log.Panic(htmlTplEngineErr.Error()) } // 其他子目錄下的模板文件 _, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*/*.html") if nil != htmlTplEngineErr { log.Panic(htmlTplEngineErr.Error()) } } // index func IndexHandler(w http.ResponseWriter, r *http.Request) { _ = htmlTplEngine.ExecuteTemplate( w, "index/index", map[string]interface{}{"PageTitle": "首頁(yè)", "Name": "sqrt_cat", "Age": 25}, ) } // news func NewsHandler(w http.ResponseWriter, r *http.Request) { _ = htmlTplEngine.ExecuteTemplate( w, "news/index", map[string]interface{}{ "PageTitle": "新聞", "List": []struct { Title string CreatedAt time.Time }{ {Title: "this is golang views/template example", CreatedAt: time.Now()}, {Title: "to be honest, i don"t very like this raw engine", CreatedAt: time.Now()}, }, "Total": 1, "Author": "big_cat", }, ) } func main() { http.HandleFunc("/", IndexHandler) http.HandleFunc("/index", IndexHandler) http.HandleFunc("/news", NewsHandler) serverErr := http.ListenAndServe(":8085", nil) if nil != serverErr { log.Panic(serverErr.Error()) } }
注意:模板對(duì)象是有名字屬性的,template.New("tplName"),如果沒(méi)有顯示的定義名字,則會(huì)使用第一個(gè)被載入的視圖文件的baseName做默認(rèn)名,比如我們使用template.ParseFiles/template.ParseGlob直接生成模板對(duì)象時(shí),沒(méi)有指定模板對(duì)象名,則會(huì)使用第一個(gè)被載入的文件,比如views/index/index.html的baseName即index.html做默認(rèn)名,而后如果tplObj.Execute方法執(zhí)行渲染時(shí),會(huì)去查找名為index.html的模板,所以常用的還是tplObj.ExecuteTemplate自己指定要渲染的模板名,省的一團(tuán)亂。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/53928.html
摘要:更好的方案模板分離原則模板分離原則將定義模板的那一部分,與的代碼邏輯分離開(kāi)來(lái),讓代碼更加優(yōu)雅且利于維護(hù)。 showImg(https://segmentfault.com/img/bVJ73t?w=800&h=316); 引言 在前端開(kāi)發(fā)中,經(jīng)常需要?jiǎng)討B(tài)添加一些元素到頁(yè)面上。那么如何通過(guò)一些技巧,優(yōu)化動(dòng)態(tài)創(chuàng)建頁(yè)面元素的方式,使得代碼更加優(yōu)雅,并且更易于維護(hù)呢?接下來(lái)我們通過(guò)研究一些實(shí)例...
摘要:更好的方案模板分離原則模板分離原則將定義模板的那一部分,與的代碼邏輯分離開(kāi)來(lái),讓代碼更加優(yōu)雅且利于維護(hù)。 showImg(https://segmentfault.com/img/bVJ73t?w=800&h=316); 引言 在前端開(kāi)發(fā)中,經(jīng)常需要?jiǎng)討B(tài)添加一些元素到頁(yè)面上。那么如何通過(guò)一些技巧,優(yōu)化動(dòng)態(tài)創(chuàng)建頁(yè)面元素的方式,使得代碼更加優(yōu)雅,并且更易于維護(hù)呢?接下來(lái)我們通過(guò)研究一些實(shí)例...
摘要:但由于和技術(shù)過(guò)于和復(fù)雜,并沒(méi)能得到廣泛的推廣。但是在瀏覽器內(nèi)并不適用。依托模塊化編程,的實(shí)現(xiàn)方式更為簡(jiǎn)單清晰,一個(gè)網(wǎng)頁(yè)不再是傳統(tǒng)的類似文檔的頁(yè)面,而是一個(gè)完整的應(yīng)用程序。到了這里,我們的主角登場(chǎng)了年此處應(yīng)有掌聲。和差不多同期登場(chǎng)的還有。 Github:https://github.com/fenivana/w...webpack 更新到了 4.0,官網(wǎng)還沒(méi)有更新文檔。因此把教程更新一下...
摘要:方法三使用調(diào)用父作用域中的函數(shù)實(shí)例地址同樣采用了缺省寫法,運(yùn)行之后,彈出窗口布爾值或者字符,默認(rèn)值為這個(gè)配置選項(xiàng)可以讓我們提取包含在指令那個(gè)元素里面的內(nèi)容,再將它放置在指令模板的特定位置。 準(zhǔn)備代碼,會(huì)在實(shí)例中用到 var app = angular.module(app, []); angular指令定義大致如下 app.directive(directiveName, functi...
摘要:方法三使用調(diào)用父作用域中的函數(shù)實(shí)例地址同樣采用了缺省寫法,運(yùn)行之后,彈出窗口布爾值或者字符,默認(rèn)值為這個(gè)配置選項(xiàng)可以讓我們提取包含在指令那個(gè)元素里面的內(nèi)容,再將它放置在指令模板的特定位置。 準(zhǔn)備代碼,會(huì)在實(shí)例中用到 var app = angular.module(app, []); angular指令定義大致如下 app.directive(directiveName, functi...
閱讀 2967·2021-10-14 09:43
閱讀 2914·2021-10-14 09:42
閱讀 4706·2021-09-22 15:56
閱讀 2387·2019-08-30 10:49
閱讀 1610·2019-08-26 13:34
閱讀 2401·2019-08-26 10:35
閱讀 627·2019-08-23 17:57
閱讀 2050·2019-08-23 17:15