dongshou9343 2017-09-05 10:10
浏览 39
已采纳

golang模板处理和泛型

I have two golang html templates, as follows:

var m map[string]string
m = make(map[string]string)

m["First"] = `<html>
<body>First template type {{.First}}
</html>`

m["Second"] = `<html>
<body>Second template type {{.SecondF1}} {{.SecondF2}}
</html>`

The first html template takes only one argument, named First whereas the second template needs two arguments, named SecondF1 and SecondF2.

Now I have a struct which has two fields, one for receiving a template name and another for receiving the template arguments.

type tmplReceiver struct {
    TmplName string
    TmplArgs string // Receives JSON string
}

Now, examples of instances for the above structs could be:

var i, j tmplReceiver

i.TmplName = "First"
i.TmplArgs = `{"Field1": "First Template Argument"}`

j.TmplName = "Second"
j.TmplArgs = `{
  "SecondF1": "Second template First Argument", 
  "SecondF2": "Second template Second Argument"
}`

Now I can get the Template string by using the map, for example:

tmplStr := m[i.TmplName] (or)
tmplStr := m[j.TmplName]

tmpl, _ = template.New("email").Parse(tmplStr)

However, how do I get the template to be executed for all the possible template types, with a single tmpl.Execute statement. In other words, if I want to have the following code:

var buff bytes.Buffer
if err := tmpl.Execute(&buff, tmplPtr); err != nil {
    log.Fatal(err)
}
log.Println(buff.String())

How do I get the tmplPtr to be valid, irrespective of how many templates I have (First, Second, etc.) and each of these templates can have a variable number of arguments (First has only one arg, whereas Second has two args, etc.)

I do not want to write N different tmpl.Execute statements with an if block for each template name. Is there any other alternative approach to solve this ? Thanks.

  • 写回答

1条回答 默认 最新

  • drsw9390405 2017-09-05 11:13
    关注

    Neither json.Unmarshal nor template.Execute cares about the actual type of the data, this will all be handled at runtime. So you can just parse the json to an interface{} and pass that to your templates. Provided that the json data contains the fields that are expected by the template to which you pass the data, this will just work fine.

    Playground link

    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "html/template"
    )
    
    var templates = map[string]*template.Template{
        "A": template.Must(template.New("A").Parse("{{ .A }}")),
        "B": template.Must(template.New("B").Parse("{{ .B }} and {{ .C.D }}")),
    }
    
    type tmplReceiver struct {
        TmplName string
        TmplArgs string
    }
    
    func main() {
        receivers := []tmplReceiver{
            tmplReceiver{"A", `{"A": "Value for A"}`},
            tmplReceiver{"B", `{"B": "Value for B", "C": { "D": "Value for D" }}`},
        }
    
        for _, receiver := range receivers {
            var data interface{}
            json.Unmarshal([]byte(receiver.TmplArgs), &data)
    
            var buffer bytes.Buffer
            templates[receiver.TmplName].Execute(&buffer, data)
            fmt.Println(buffer.String())
        }
    }
    

    Which prints

    Value for A

    Value for B and Value for D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥15 this signal is connected to multiple drivers怎么解决
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus