github.com/docker/docker-ce@v17.12.1-ce-rc2+incompatible/components/cli/templates/templates.go (about) 1 package templates 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "strings" 7 "text/template" 8 ) 9 10 // basicFunctions are the set of initial 11 // functions provided to every template. 12 var basicFunctions = template.FuncMap{ 13 "json": func(v interface{}) string { 14 buf := &bytes.Buffer{} 15 enc := json.NewEncoder(buf) 16 enc.SetEscapeHTML(false) 17 enc.Encode(v) 18 // Remove the trailing new line added by the encoder 19 return strings.TrimSpace(buf.String()) 20 }, 21 "split": strings.Split, 22 "join": strings.Join, 23 "title": strings.Title, 24 "lower": strings.ToLower, 25 "upper": strings.ToUpper, 26 "pad": padWithSpace, 27 "truncate": truncateWithLength, 28 } 29 30 // HeaderFunctions are used to created headers of a table. 31 // This is a replacement of basicFunctions for header generation 32 // because we want the header to remain intact. 33 // Some functions like `split` are irrelevant so not added. 34 var HeaderFunctions = template.FuncMap{ 35 "json": func(v string) string { 36 return v 37 }, 38 "title": func(v string) string { 39 return v 40 }, 41 "lower": func(v string) string { 42 return v 43 }, 44 "upper": func(v string) string { 45 return v 46 }, 47 "truncate": func(v string, _ int) string { 48 return v 49 }, 50 } 51 52 // Parse creates a new anonymous template with the basic functions 53 // and parses the given format. 54 func Parse(format string) (*template.Template, error) { 55 return NewParse("", format) 56 } 57 58 // New creates a new empty template with the provided tag and built-in 59 // template functions. 60 func New(tag string) *template.Template { 61 return template.New(tag).Funcs(basicFunctions) 62 } 63 64 // NewParse creates a new tagged template with the basic functions 65 // and parses the given format. 66 func NewParse(tag, format string) (*template.Template, error) { 67 return New(tag).Parse(format) 68 } 69 70 // padWithSpace adds whitespace to the input if the input is non-empty 71 func padWithSpace(source string, prefix, suffix int) string { 72 if source == "" { 73 return source 74 } 75 return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix) 76 } 77 78 // truncateWithLength truncates the source string up to the length provided by the input 79 func truncateWithLength(source string, length int) string { 80 if len(source) < length { 81 return source 82 } 83 return source[:length] 84 }