Go html/template 模板的使用實例

從字符串載入模板

我們可以定義模板字符串,然後載入並解析渲染:

template.New(tplName string).Parse(tpl string)

// 從字符串模板構建
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})

從文件載入模板

模板語法

模板文件,建議爲每個模板文件顯式的定義模板名稱:{{ define "tplName" }},否則會因模板對象名與模板名不一致,無法解析(條件分支很多,不如按一種標準寫法實現),另展示一些基本的模板語法。

  • 使用 {{ define "tplName" }} 定義模板名
  • 使用 {{ template "tplName" . }}引入其他模板
  • 使用 . 訪問當前數據域:比如range裏使用.訪問的其實是循環項的數據域
  • 使用 $. 訪問絕對頂層數據域

views/header.html

{{ define "header" }}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ .PageTitle }}</title>
</head>
{{ end }}

views/footer.html

{{ define  "footer" }}
</html>
{{ end }}

views/index/index.html

{{ define "index/index" }}
    {{/*引用其他模板 注意後面的 . */}}
    {{ template "header" . }}
    <body>
    <div>
        hello, {{ .Name }}, age {{ .Age }}
    </div>
    </body>
    {{ template "footer" . }}
{{ end }}

views/news/index.html

{{ define "news/index" }}
    {{ template "header" . }}
    <body>
    {{/* 頁面變量定義 */}}
    {{ $pageTitle := "news title" }}
    {{ $pageTitleLen := len $pageTitle }}
    {{/* 長度 > 4 才輸出 eq ne gt lt ge le */}}
    {{ if gt $pageTitleLen 4 }}
        <h4>{{ $pageTitle }}</h4>
    {{ end }}

    {{ $c1 := gt 4 3}}
    {{ $c2 := lt 2 3 }}
    {{/*and or not 條件必須爲標量值 不能是邏輯表達式 如果需要邏輯表達式請先求值*/}}
    {{ if and $c1 $c2 }}
        <h4>1 == 1 3 > 2 4 < 5</h4>
    {{ end }}

    <div>
        <ul>
            {{ range .List }}
                {{ $title := .Title }}
                {{/* .Title 上下文變量調用    func param1 param2 方法/函數調用   $.根節點變量調用 */}}
                <li>{{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}</li>
            {{end}}
        </ul>
        {{/* !empty Total 才輸出*/}}
        {{ with .Total }}
            <div>總數:{{ . }}</div>
        {{ end }}
    </div>
    </body>
    {{ template "footer" . }}
{{ end }}

template.ParseFiles

手動定義需要載入的模板文件,解析後製定需要渲染的模板名news/index

// 從模板文件構建
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: "首頁",
        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

手動的指定每一個模板文件,在一些場景下難免難以滿足需求,我們可以使用通配符正則匹配載入。

1、正則不應包含文件夾,否則會因文件夾被作爲視圖載入無法解析而報錯
2、可以設定多個模式串,如下我們載入了一級目錄和二級目錄的視圖文件
// 從模板文件構建
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: "首頁",
        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服務器

結合模板庫和Gin實現一個可以使用模板渲染並返回html頁面的web服務。

package main

import (
    "html/template"
    "log"
    "net/http"
    "time"
)

var (
    htmlTplEngine    *template.Template
    htmlTplEngineErr error
)

func init() {
    // 初始化模板引擎 並加載各層級的模板文件
    // 注意 views/* 不會對子目錄遞歸處理 且會將子目錄匹配 作爲模板處理造成解析錯誤
    // 若存在與模板文件同級的子目錄時 應指定模板文件擴展名來防止目錄被作爲模板文件處理
    // 然後通過 view/*/*.html 來加載 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": "首頁", "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())
    }
}

注意:模板對象是有名字屬性的,template.New("tplName"),如果沒有顯示的定義名字,則會使用第一個被載入的視圖文件的baseName做默認名,比如我們使用template.ParseFiles/template.ParseGlob直接生成模板對象時,沒有指定模板對象名,則會使用第一個被載入的文件,比如views/index/index.htmlbaseNameindex.html做默認名,而後如果tplObj.Execute方法執行渲染時,會去查找名爲index.html的模板,所以常用的還是tplObj.ExecuteTemplate自己指定要渲染的模板名,省的一團亂。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章