golang Format string by key.

example:

$ go get github.com/hoisie/mustache

 1 package main
 2 
 3 import (
 4     "github.com/hoisie/mustache"
 5 
 6     "bytes"
 7     "fmt"
 8     "strings"
 9     "text/template"
10 )
11 
12 
13 func FormatByKey(f string, m map[string]interface{}) (string, error) {
14     var tpl bytes.Buffer
15     t := template.Must(template.New("").Parse(f))
16     if err := t.Execute(&tpl, m); err != nil {
17         return f, err
18     }
19     return tpl.String(), nil
20 }
21 
22 func main() {
23     // use mustache
24     m1 := map[string]interface{}{"age": "47", "c": "world"}
25     data := mustache.Render("hello {{c}}, I'm {{age}} years old.\n", m1)
26     println(data)
27 
28     // use golang native template
29     m := map[string]interface{}{"name": "John", "age": 47}
30     s := "I'm {{.name}}, I'm {{.age}} years old.Hi {{.name}}. Your age is {{.age}}\n"
31     fmt.Println(FormatByKey(s, m))
32 
33     //strings.NewReplacer
34     ss := []string{"{{.name}}", "John", "{{.age}}", "47"}
35     r := strings.NewReplacer(ss...)
36     fmt.Println(r.Replace(s))
37 }

 

$ go run test.go

 

another example.

 

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "strings"
 6 )
 7 
 8 func main() {
 9     Tprintf("Hello %{Name}s %{Apos}s", map[string]interface{}{"Name": "GoLang", "Apos": "!"})
10 }
11 
12 func Tprintf(format string, params map[string]interface{}) {
13     for key, val := range params {
14         format = strings.Replace(format, "%{"+key+"}s", fmt.Sprintf("%s", val), -1)
15     }
16     fmt.Printf(format)
17 }

 

Named String Formatting

Golang Template is powerful 

posted @ 2017-09-05 17:40  lvmxh  阅读(538)  评论(0编辑  收藏  举报