如何使用 html 模板解组结构?

How to unmarshal struct with html template?

我正在尝试将 JSON 解组到我的 Mail 结构,但是在解析 html_tmpl 和 text_tmpl 字段时 Go returns 出错。 我该如何解决这个问题?

HtmlTmpl 字段来自:

html, err := template.ParseFiles(pathToHTMLFile)

这是您可以测试的基本示例

package main

import (
    "encoding/json"
    "fmt"
    "html/template"
    "time"
)

type Mail struct {
    Id       string            `json:"id"`
    Subject  string            `json:"subject"`
    From     string            `json:"from"`
    To       string            `json:"to"`
    Date     time.Time         `json:"date"`
    HtmlTmpl template.Template `json:"html_tmpl"`
    TextTmpl template.Template `json:"text_tmpl"`
    Context  map[string]string `json:"context"`
}

func main() {
  mail := &Mail{}
  s := `{"id":"","subject":"Test mail","from":"support@example.com","to":"user@gmail.com","date":"0001-01-01T00:00:00Z","html_tmpl":{"Tree":{"Name":"template.html","ParseName":"template.html","Root":{"NodeType":11,"Pos":0,"Nodes":[{"NodeType":0,"Pos":0,"Text":"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9InJ1Ij4KPGhlYWQ+Cgk8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQvaHRtbCIgY2hhcnNldD0iVVRGLTgiPgoJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgaW5pdGlhbD0xIj4KCTxtZXRhIGh0dHAtZXF1aXY9IlgtVUEtQ29tcGF0aWJsZSIgY29udGVudD0iSUU9ZWRnZSI+Cgk8dGl0bGU+0J/RgNC+0LLQtdGA0LrQsCDRgdCy0Y/Qt9C4PC90aXRsZT4KPC9oZWFkPgo8Ym9keT4KCTxzcGFuPg=="},{"NodeType":1,"Pos":298,"Line":10,"Pipe":{"NodeType":14,"Pos":298,"Line":10,"IsAssign":false,"Decl":null,"Cmds":[{"NodeType":4,"Pos":298,"Args":[{"NodeType":8,"Pos":298,"Ident":["msg"]}]}]}},{"NodeType":0,"Pos":305,"Text":"PC9zcGFuPgo8L2JvZHk+CjwvaHRtbD4="}]}}},"text_tmpl":{"Tree":{"Name":"template.txt","ParseName":"template.txt","Root":{"NodeType":11,"Pos":0,"Nodes":[{"NodeType":1,"Pos":2,"Line":1,"Pipe":{"NodeType":14,"Pos":2,"Line":1,"IsAssign":false,"Decl":null,"Cmds":[{"NodeType":4,"Pos":2,"Args":[{"NodeType":8,"Pos":2,"Ident":["msg"]}]}]}}]}}},"context":{"msg":"Hi!"}}`
  err := json.Unmarshal([]byte(s), mail)

  fmt.Println(err)
  fmt.Println(mail)
}

template.Template does not support marshaling into / unmarshaling from JSON. It's a struct with unexported fields, and it does not implement an interface that handles the marshaling / unmarshaling logic (such as json.Unmarshaler).

您应该做的是在您的 JSON 和结构中包含 源模板文本 ,并在解组源模板文本后,将其解析为 post 处理步骤。如果你想编组一个包含模板的结构,它应该只包含源模板文本(template.Template 字段应该被标记为省略,比如 json:"-")。