zoukankan      html  css  js  c++  java
  • 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.
    ", 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}}
    "
    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 

  • 相关阅读:
    你不是真正的快乐
    春天里
    一生有你
    故乡
    第一天
    直来直往
    恋恋风尘
    烦恼歌
    because of you
    从头再来
  • 原文地址:https://www.cnblogs.com/shaohef/p/7479810.html
Copyright © 2011-2022 走看看