Zuzanna Deger
Zuzanna Deger

Reputation: 9

Referencing map values in Go text/template

I have a Golang string:

 var expressions: = `
{ "text1": "lorem ipsum {{value1}}/12" 
   "text1": "lorem ipsum {{value2}}/24" 
}
`

and a map :

  constants:= map[string]int{
   "value1": 3711,
   "value2":   2138,  
}

How to replace values in expressions with corresponding values in the map?

Upvotes: 0

Views: 681

Answers (1)

Kamol Hasan
Kamol Hasan

Reputation: 13496

To use the value of a map, you need to specify the name of the key of that field preceded by a period(.), such as .keyName.

package main

import (
    "os"
    "text/template"
)

func main() {
    var err error
    constants := map[string]int{
        "value1": 3711,
        "value2": 2138,
    }

    tmpl := `{ 
    "text1": "lorem ipsum {{ .value1 }}/12" 
    "text2": "lorem ipsum {{ .value2 }}/24" 
}`

    t := template.New("hello")
    tt, err := t.Parse(tmpl)
    if err != nil {
        panic(err)
    }

    if err = tt.Execute(os.Stdout, &constants); err != nil {
        panic(err)
    }
}

Output:

{ 
    "text1": "lorem ipsum 3711/12" 
    "text2": "lorem ipsum 2138/24" 
}

Go Playground

For more complex use-cases, you can take a look at this code.

Upvotes: 1

Related Questions