github.com/aminjam/goflat@v0.4.1-0.20160331105230-ec639fc0d5b3/runtime/pipes.go (about) 1 package runtime 2 3 import ( 4 "reflect" 5 "strings" 6 "text/template" 7 ) 8 9 type Pipes struct { 10 Map template.FuncMap 11 } 12 13 func (p *Pipes) Extend(fm template.FuncMap) { 14 for k, v := range fm { 15 p.Map[k] = v 16 } 17 } 18 19 func NewPipes() *Pipes { 20 return &Pipes{ 21 Map: template.FuncMap{ 22 "join": func(sep string, a []string) (string, error) { 23 return strings.Join(a, sep), nil 24 }, 25 //e.g. map "Name,Age,Job" "|" => "[John|25|Painter Jane|21|Teacher]" 26 "map": func(f, sep string, a interface{}) ([]string, error) { 27 fields := strings.Split(f, ",") 28 reflectedArray := reflect.ValueOf(a) 29 out := make([]string, reflectedArray.Len()) 30 i := 0 31 for i < len(out) { 32 v := reflectedArray.Index(i) 33 row := make([]string, len(fields)) 34 for k, field := range fields { 35 row[k] = v.FieldByName(field).String() 36 } 37 out[i] = strings.Join(row, sep) 38 i++ 39 } 40 return out, nil 41 }, 42 "replace": func(old, new, s string) (string, error) { 43 //replace all occurrences of a value 44 return strings.Replace(s, old, new, -1), nil 45 }, 46 "split": func(sep, s string) ([]string, error) { 47 s = strings.TrimSpace(s) 48 if s == "" { 49 return []string{}, nil 50 } 51 return strings.Split(s, sep), nil 52 }, 53 "toUpper": func(s string) (string, error) { 54 return strings.ToUpper(s), nil 55 }, 56 "toLower": func(s string) (string, error) { 57 return strings.ToLower(s), nil 58 }, 59 }, 60 } 61 }