一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Golang - Go html/template 模板的使用實例詳解

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

2020-05-25 10:40big_cat Golang

這篇文章主要介紹了Go html/template 模板的使用實例詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

從字符串載入模板

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

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

?
1
2
3
4
5
6
7
// 從字符串模板構建
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{{ 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

?
1
2
3
4
5
6
7
8
9
10
{{ define "index/index" }}
  {{/*引用其他模板 注意后面的 . */}}
  {{ template "header" . }}
  <body>
  <div>
    hello, {{ .Name }}, age {{ .Age }}
  </div>
  </body>
  {{ template "footer" . }}
{{ end }}

views/news/index.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{{ 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 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 從模板文件構建
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、可以設定多個模式串,如下我們載入了一級目錄和二級目錄的視圖文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 從模板文件構建
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 服務。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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.html 的 baseName 即 index.html 做默認名,而后如果 tplObj.Execute 方法執行渲染時,會去查找名為 index.html 的模板,所以常用的還是 tplObj.ExecuteTemplate 自己指定要渲染的模板名,省的一團亂。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://studygolang.com/articles/20713

延伸 · 閱讀

精彩推薦
  • Golanggolang如何使用struct的tag屬性的詳細介紹

    golang如何使用struct的tag屬性的詳細介紹

    這篇文章主要介紹了golang如何使用struct的tag屬性的詳細介紹,從例子說起,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看...

    Go語言中文網11352020-05-21
  • Golanggolang 通過ssh代理連接mysql的操作

    golang 通過ssh代理連接mysql的操作

    這篇文章主要介紹了golang 通過ssh代理連接mysql的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    a165861639710342021-03-08
  • GolangGolang中Bit數組的實現方式

    Golang中Bit數組的實現方式

    這篇文章主要介紹了Golang中Bit數組的實現方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    天易獨尊11682021-06-09
  • Golanggo語言制作端口掃描器

    go語言制作端口掃描器

    本文給大家分享的是使用go語言編寫的TCP端口掃描器,可以選擇IP范圍,掃描的端口,以及多線程,有需要的小伙伴可以參考下。 ...

    腳本之家3642020-04-25
  • Golanggolang的httpserver優雅重啟方法詳解

    golang的httpserver優雅重啟方法詳解

    這篇文章主要給大家介紹了關于golang的httpserver優雅重啟的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,...

    helight2992020-05-14
  • Golanggolang json.Marshal 特殊html字符被轉義的解決方法

    golang json.Marshal 特殊html字符被轉義的解決方法

    今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉義的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    李浩的life12792020-05-27
  • GolangGolang通脈之數據類型詳情

    Golang通脈之數據類型詳情

    這篇文章主要介紹了Golang通脈之數據類型,在編程語言中標識符就是定義的具有某種意義的詞,比如變量名、常量名、函數名等等,Go語言中標識符允許由...

    4272021-11-24
  • Golanggo日志系統logrus顯示文件和行號的操作

    go日志系統logrus顯示文件和行號的操作

    這篇文章主要介紹了go日志系統logrus顯示文件和行號的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    SmallQinYan12302021-02-02
主站蜘蛛池模板: 国产精品成人麻豆专区 | 国产九九视频在线观看 | 97se狠狠狠狠狼亚洲综合网 | 啪啪无尽3d动漫漫画免费网站 | 久久这里只有精品视频9 | 婷婷婷色 | 36美女厕所撒尿全过程 | 日本wwxx护士 | 狠狠干2017| 免费看打屁股视频的软件 | 洗濯屋し在线观看 | 美女视频ww8888网网 | 99久精品| 国产精品福利久久2020 | 女人全身裸露无遮挡免费观看 | 国产成+人+亚洲+欧美综合 | 美女私人影院 | 女子监狱第二季在线观看免费完整版 | 青青草国产免费国产是公开 | 成人软件18免费 | xxx美国 | 欧美高清免费一级在线 | 二区三区不卡不卡视频 | 日本三级在线观看免费 | 91人成网站色www | 884hutv四虎永久7777 | 久久热在线视频精品1 | 成人在线观看免费视频 | 全黄一级裸片视频免费 | 免费看国产精品久久久久 | 久久久精品日本一区二区三区 | 韩国漂亮美女三级在线观看 | 高h生子双性美人受 | 久久久WWW免费人成精品 | 99爱免费 | 亚洲黄色天堂 | 日本68xxxxxxxxx24 日本 片 成人 在线 | 亚洲欧美日韩综合在线播放 | 母性本能| 精品亚洲国产一区二区 | 无毛黄片 |