dousuochu7291 2017-08-10 10:36
浏览 28
已采纳

在Go HTML模板中创建结构映射键的语法

I'm writing a simple Go program to display an HTML table of deployed service versions per environment. My program contains the following structs:

type versionKey struct {
    Environment string
    Service     string
}

type templateData struct {
    Environments []string
    Services     []string
    Versions     map[versionKey]string
}

As you can see, the Versions map uses a versionKey as a key for a string value e.g. "1.0.0".

I'm passing the templateData struct to an HTML template and ranging over its Environments and Services slices to build the HTML table. The problem is that I need to construct a versionKey for any given intersection of environment and service so I can use it to look up the version from the Versions map and output that value in the table cell.

Within the template I have $environment and $service variables available from the ranges, but I can't work out the Go template syntax to create the versionKey struct.

Here's the template code with the markup omitted:

{{$environments := .Environments}}
{{$services := .Services}}
{{$versions := .Versions}}

{{range $service := $services}}
  ...
  {{range $environment := $environments}}
    ...
    {{index $versions ...? }} // How to create versionKey struct map key here?
    ...
  {{end}}
  ...
{{end}}
  • 写回答

1条回答 默认 最新

  • douzhang2680 2017-08-10 11:13
    关注

    Using only template code you can't. You need some kind of support from the executing Go code to do that. By design philosophy, templates should not contain complex logic. You may argue whether this is complex, but the template syntax has no support for this.

    Simplest solution would be to add a Version() method to the templateData struct, which would simply return the version for a given environment and service:

    func (t *templateData) Version(environment, service string) string {
        return t.Versions[versionKey{
            Environment: environment,
            Service:     service,
        }]
    }
    

    Using this from the template:

    {{range $service := $services -}}
      {{range $environment := $environments}}
        {{$environment}} - {{$service}} version: {{$.Version $environment $service}}
      {{end}}
    {{end}}
    

    Testing it:

    t := template.Must(template.New("").Parse(templ))
    td := &templateData{
        Environments: []string{"EnvA", "EnvB"},
        Services:     []string{"ServA", "ServB"},
        Versions: map[versionKey]string{
            {"EnvA", "ServA"}: "1.0.0",
            {"EnvA", "ServB"}: "1.0.1",
            {"EnvB", "ServA"}: "1.0.2",
        },
    }
    if err := t.Execute(os.Stdout, td); err != nil {
        panic(err)
    }
    

    Output (try it on the Go Playground):

    EnvA - ServA version: 1.0.0
    
    EnvB - ServA version: 1.0.2
    
    
    EnvA - ServB version: 1.0.1
    
    EnvB - ServB version: 
    

    Alternatives

    Instead of the templateData.Version() method you could just as easily register a function which could create and return a value of type versionKey from a given environment and service. See Template.Funcs() for details. This would be more complicated though, but more flexible as this could be reused elsewhere. See an example of this here: Golang templates (and passing funcs to template). A slight variation of this would be to pass a function value as any other template data instead of registering it as a named function, which can be called.

    Another alternative would be to "transform" your Versions field into a map of maps, e.g.:

    Versions map[string]map[string]string
    

    Which first could be indexed by environment, then by service, which in the template you can achieve by 2 {{index}} actions. You would have to check if the first indexing yields any results though.

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助