How to print the value of a key containing dots

前端 未结 4 1215
清歌不尽
清歌不尽 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:21

    As @martin-ghallager said, one needs to use an external function to access those elements.

    Helpfully, the standard library already provides the index function (which does exactly what Martin's dotNotation function does).

    To use it just write:

    {{ index .Data "core.value" }}
    

    The index function will return a default value in case the key is not present. This works if your dictionary has homogeneous data, however it will return the wrong value when it is heterogeneous. In such a case you can explicitly set the default with:

    {{ 0 | or (index .Data "core.value") }}
    

提交回复
热议问题