0

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?

1
  • 1
    {{value1}} is a function call. Use {{.value1}} to get the value1 field of dot. Commented Apr 1, 2020 at 4:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.