­

[golang]text/template模板

  • 2019 年 10 月 7 日
  • 筆記

這個可以用來處理text文本,不過我更偏愛做成程式碼生成器。

[golang]text/template模板

package main    import (      "os"      "text/template"    )    func main() {      name := "testfuck"      tmp,e := template.New("bbb").Parse("這是,{{.}}") //建立模板      if e != nil {          panic(e)      }      e =tmp.Execute(os.Stdout,name) //將string與模板合成,變數name的內容會替換掉{{.}}      //合成結果放到os.Stdout里      if e !=nil{          panic(e)      }    }

運行結果

這是,testfuck

#go語言的模板,text/template包 ##定義 模板就是將一組文本嵌入另一組文本里

##傳入string–最簡單的替換

package main    import (      "os"      "text/template"  )    func main() {      name := "waynehu"      tmpl, err := template.New("test").Parse("hello, {{.}}") //建立一個模板,內容是"hello, {{.}}"      if err != nil {              panic(err)      }      err = tmpl.Execute(os.Stdout, name)  //將string與模板合成,變數name的內容會替換掉{{.}}      //合成結果放到os.Stdout里      if err != nil {              panic(err)      }  }  //輸出 :   hello, waynehu