Escaping a dot in a template variable

I am feeding data from an external json source (over which I have no control) into a template. But some of the names have dot’s in them. So I end up with a template
variable {{.Map.first.name}} where “first.name” is a key in Map. How do I escape the dot? Or is there
some other trick? I’ve tried {{.Map.“first.name”}} but that produces a panic (bad character ‘"’).

Here is a sample program that illustrates the problem.

Many thanks

package main

import (
        "os"
        "text/template"
        "time"
)

const atemplate = `Look at this:
{{range .}} {{.Name}} {{.Count }} 
{{.JoinDate}} {{.JoinString}} {{.Map.post.code}}
{{end}}`

type Record struct {
        Name       string
        Count      int
        JoinDate   time.Time
        JoinString string
        Map        map[string]string
}

func main() {
        tmpl, err := template.New("test").Parse(atemplate)
        if err != nil {
                panic(err)
        }
        var r []Record
        r = append(r, Record{
                Name:       "Suzanne",
                Count:      236,
                JoinDate:   time.Date(2009, time.November, 10, 23, 0, 0, 0, time.Local),
                JoinString: "rs",
                Map:        map[string]string{"key": "value", "post.code": "5068"},
        })
        err = tmpl.Execute(os.Stdout, r)
        if err != nil {
                panic(err)
        }
}

You should be able to use index function in the template.

{{index .Map "post.code"}}

Or, if you know the keys in advance, don’t dump into a map[string]string, but unmarshall into a properly defined struct.

type TheForeignJson struct {
  PostCode string `json:"post.code"`
}

type Record struct {
        Name       string
        Count      int
        JoinDate   time.Time
        JoinString string
        Map        TheForeignJson
}

Many thanks. Your solution {{index … }} works in my test code, but not in the real code … so the structure I’m working with is obviously different from what I think it is! The data is coming from the github.com/stripe/stripe-go module. I have to dig deeper :slight_smile:

The only occurrence of a key that starts with post on the API documentation page was a postal_code.

Yes … the problem isn’t with the Stripe variables … but with a bunch of metadata variables being added by other applications. Stripe lets clients add metadata maps and I’m trying to summarise charge data generated by 3 different applications all of which use different names in the metadata :frowning: … and some of the names have dots and some have spaces.

But I’ve discovered my wrong assumption in the structure and the “index” function works fine. Many thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.