iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
Modern Web

還喝不 go系列 第 16

[13th][Day16] tamplete

golang template
golang stdlib(標準函式庫)中提供兩種跟 template 有關的 package

text/template    
html/template

來看看關於 html/template 的官方解釋

https://golang.org/pkg/html/template/

Package template implements data-driven templates for generating textual output.

Package template 為了產生文本,實現了資料驅動模板

To generate HTML output, see package html/template, which has the same interface as this package but automatically secures HTML output against certain attacks.

為了產生 HTML 輸出,可以看看 package html/template ,它與 text/template 擁有一樣的接口,但會自動保護HTML輸出,阻擋一些攻擊

這麼一大串的英文主要講得也就是 資料驅動編程這東東

而實際上的應用 ... 就直接進入 code 的部分吧

首先在 main 的外面宣告一個模板,他是一個 string

var demoString = "noChange1: {{.Value1}} \nnoChange2: {{.Value2}}"

我用了 \n 來換行

宣告一個 struct

type demoStruct struct {
	Value1 int64
	Value2 int64
}

在 func main() 中宣告一個 struct 值 的 址
注意:demoPointer 的型態為 *demoStruct

    demoPointer := &demoStruct{
		Value1: 9487,
		Value2: 9453,
	}

宣告一個 byte buffer

var tpl bytes.Buffer

使用 package html/template 的 must 方法產生 *template.Template
Parse 後,再使用 t.Execute 方法就可以完成給值

	t := template.Must(template.New("").Parse(demoString))
	if err := t.Execute(&tpl, demoPointer); err != nil {
		fmt.Println(err)
		return
	}

最後,終於可以用 fmt.Println 印出來囉

完整程式碼

package main

import (
	"bytes"
	"fmt"
	"html/template"
)

var demoString = "noChange1: {{.Value1}} \nnoChange2: {{.Value2}}"

type demoStruct struct {
	Value1 int64
	Value2 int64
}

func main() {
	demoPointer := &demoStruct{
		Value1: 9487,
		Value2: 9453,
	}

	var tpl bytes.Buffer
	t := template.Must(template.New("").Parse(demoString))
	if err := t.Execute(&tpl, demoPointer); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(tpl.String())
}
輸出為

noChange1: 9487 
noChange2: 9453
注意變數的大小寫會影響作用域&傳遞範圍


上一篇
[13th][Day15] nil
下一篇
[13th][Day17] tamplete range
系列文
還喝不 go23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言