How to print the value of a key containing dots

前端 未结 4 1220
清歌不尽
清歌不尽 2021-02-12 09:39

I\'m trying to print the values of a map, whose keys have a dot (.) on it.

Example map:

type TemplateData struct {
    Data map[string] int
         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-12 10:12

    As fabrizioM has stated, it's against the specs of the package, however there's nothing stopping you creating your own accessor to use dot notation using a function map:

    package main
    
    import (
        "fmt"
        "html/template"
        "os"
    )
    
    type TemplateData struct {
        Data map[string]int
    }
    
    var funcMap = template.FuncMap{
        "dotNotation": dotNotation,
    }
    
    func main() {
        data := TemplateData{map[string]int{"core.value": 1, "test": 100}}
    
        t, err := template.New("foo").Funcs(funcMap).Parse(`{{dotNotation .Data "core.value"}}`)
    
        if err != nil {
            fmt.Println(err)
        }
    
        err = t.Execute(os.Stdout, data)
    
        if err != nil {
            fmt.Println(err)
        }
    }
    
    func dotNotation(m map[string]int, key string) int {
        // Obviously you'll need to validate existence / nil map
        return m[key]
    }
    

    http://play.golang.org/p/-rlKFx3Ayt

提交回复
热议问题