欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go html/template 模板的使用實例詳解

 更新時間:2019年05月31日 15:13:19   作者:big_cat  
這篇文章主要介紹了Go html/template 模板的使用實例詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

從字符串載入模板

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

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})

從文件載入模板

模板語法

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

  • 使用 {{ define "tplName" }} 定義模板名
  • 使用 {{ template "tplName" . }} 引入其他模板
  • 使用 . 訪問當(dāng)前數(shù)據(jù)域:比如 range 里使用 . 訪問的其實是循環(huán)項的數(shù)據(jù)域
  • 使用 $. 訪問絕對頂層數(shù)據(jù)域

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 條件必須為標(biāo)量值 不能是邏輯表達(dá)式 如果需要邏輯表達(dá)式請先求值*/}}
  {{ if and $c1 $c2 }}
    <h4>1 == 1 3 > 2 4 < 5</h4>
  {{ end }}

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

template.ParseFiles

手動定義需要載入的模板文件,解析后制定需要渲染的模板名 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: "首頁",
    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、正則不應(yīng)包含文件夾,否則會因文件夾被作為視圖載入無法解析而報錯

2、可以設(shè)定多個模式串,如下我們載入了一級目錄和二級目錄的視圖文件

// 從模板文件構(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: "首頁",
    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é)合模板庫和 Gin 實現(xiàn)一個可以使用模板渲染并返回 html 頁面的 web 服務(wù)。

package main

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

var (
  htmlTplEngine  *template.Template
  htmlTplEngineErr error
)

func init() {
  // 初始化模板引擎 并加載各層級的模板文件
  // 注意 views/* 不會對子目錄遞歸處理 且會將子目錄匹配 作為模板處理造成解析錯誤
  // 若存在與模板文件同級的子目錄時 應(yīng)指定模板文件擴(kuò)展名來防止目錄被作為模板文件處理
  // 然后通過 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 做默認(rèn)名,比如我們使用 template.ParseFiles/template.ParseGlob 直接生成模板對象時,沒有指定模板對象名,則會使用第一個被載入的文件,比如 views/index/index.html 的 baseName 即 index.html 做默認(rèn)名,而后如果 tplObj.Execute 方法執(zhí)行渲染時,會去查找名為 index.html 的模板,所以常用的還是 tplObj.ExecuteTemplate 自己指定要渲染的模板名,省的一團(tuán)亂。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • sublime安裝支持go和html的插件

    sublime安裝支持go和html的插件

    這篇文章主要介紹了sublime安裝支持go和html的插件,需要的朋友可以參考下
    2015-01-01
  • Go 語言入門學(xué)習(xí)之正則表達(dá)式

    Go 語言入門學(xué)習(xí)之正則表達(dá)式

    這篇文章主要介紹了Go 語言入門學(xué)習(xí)之正則表達(dá)式,文章基于GO語言的相關(guān)資料展開詳細(xì)內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-04-04
  • 一文詳解Go語言中的Defer機(jī)制

    一文詳解Go語言中的Defer機(jī)制

    在Go語言中,defer是一個關(guān)鍵字,用于確保資源的清理和釋放,特別是在函數(shù)中創(chuàng)建的資源,下面就跟隨小編一起來了解下Defer機(jī)制的具體使用吧
    2024-11-11
  • Go語言入門之基礎(chǔ)語法和常用特性解析

    Go語言入門之基礎(chǔ)語法和常用特性解析

    這篇文章主要給大家講解了Go語言的基礎(chǔ)語法和常用特性解析,比較適合入門小白,文中通過代碼示例介紹的非常詳細(xì),對我們學(xué)習(xí)Go語言有一定的幫助,需要的朋友可以參考下
    2023-07-07
  • go集成gorm數(shù)據(jù)庫的操作代碼

    go集成gorm數(shù)據(jù)庫的操作代碼

    GORM 是一個用于 Go 語言的 ORM(對象關(guān)系映射)庫,它提供了一種簡單而強(qiáng)大的方式來與數(shù)據(jù)庫進(jìn)行交互,GORM 支持多種數(shù)據(jù)庫,并且提供了豐富的功能,如自動遷移、預(yù)加載、事務(wù)管理等,文中通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下
    2024-11-11
  • go?smtp實現(xiàn)郵件發(fā)送示例詳解

    go?smtp實現(xiàn)郵件發(fā)送示例詳解

    這篇文章主要為大家介紹了go?smtp實現(xiàn)郵件發(fā)送示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 使用Golang實現(xiàn)AES加解密的代碼示例

    使用Golang實現(xiàn)AES加解密的代碼示例

    在現(xiàn)代的數(shù)據(jù)安全中,加密和解密是極其重要的一環(huán),其中,高級加密標(biāo)準(zhǔn)(AES)是最廣泛使用的加密算法之一,本文將介紹如何使用Golang來實現(xiàn)AES加密和解密,需要的朋友可以參考下
    2024-04-04
  • go中值傳遞和指針傳遞的使用

    go中值傳遞和指針傳遞的使用

    在Go語言中,使用&和*可以分別取得變量的地址和值,解引用未初始化或為nil的指針會引發(fā)空指針異常,正確的做法是先進(jìn)行nil檢查,此外,nil在Go中用于多種類型的空值表示,值傳遞和指針傳遞各有適用場景,通常小型數(shù)據(jù)結(jié)構(gòu)優(yōu)先考慮值傳遞以減少解引用開銷
    2024-10-10
  • 詳解如何使用Go語言進(jìn)行文件監(jiān)控和通知

    詳解如何使用Go語言進(jìn)行文件監(jiān)控和通知

    在Go語言中,文件監(jiān)控通常涉及到文件系統(tǒng)事件的監(jiān)聽,文件或目錄的狀態(tài)發(fā)生變化(如創(chuàng)建、刪除、修改等)時,你的程序需要得到通知,所以本文給大家介紹了如何使用Go語言進(jìn)行文件監(jiān)控和通知,需要的朋友可以參考下
    2024-06-06
  • golang獲取用戶輸入的幾種方式

    golang獲取用戶輸入的幾種方式

    這篇文章給大家介紹了golang獲取用戶輸入的幾種方式,文中通過代碼示例給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友跟著小編一起來學(xué)習(xí)吧
    2024-01-01

最新評論