Skip to content

20180228_simply output go html template execution to strings

Shawn Wang edited this page Jun 5, 2018 · 1 revision

title: "將 Go Html Template 存入 String 變數" date: 2018-02-28 type: blog author: AppleBoy link: https://blog.wu-boy.com/2018/02/simply-output-go-html-template-execution-to-strings/ layout: post comments: true

Go-brown-side.sh

Go 語言內通常都將 Html Temaple 寫入到 io.Writer interface 像是 *http.ResponseWriter,但是有些情境需要將 Template 寫入到 String 變數內,例如實作簡訊 Template,這時候需要將 Html Temaple 轉成 String。該如何實作,非常簡單,只需要在任意變數內實作 io.Writer interface 即可,而 String 該如何轉換呢?可以使用 buffer’s pointer

func GetString(filename string, data interface{}) (string, error) {
    t := template.New(filename).Funcs(NewFuncMap())

    content, err := ReadFile(filename)

    if err != nil {
        logrus.Warnf("Failed to read builtin %s template. %s", filename, err)
        return "", err
    }

    t.Parse(
        string(content),
    )

    var tpl bytes.Buffer
    if err := t.Execute(&tpl, data); err != nil {
        return "", err
    }

    return tpl.String(), nil
}

其中 ReadFile 是讀取檔案函式,NewFuncMap 則是 Function Map

Clone this wiki locally