github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/pkg/templates/templates.go (about)

     1  package templates
     2  
     3  import (
     4  	"encoding/json"
     5  	"strings"
     6  	"text/template"
     7  )
     8  
     9  // basicFunctions are the set of initial
    10  // functions provided to every template.
    11  var basicFunctions = template.FuncMap{
    12  	"json": func(v interface{}) string {
    13  		a, _ := json.Marshal(v)
    14  		return string(a)
    15  	},
    16  	"split":    strings.Split,
    17  	"join":     strings.Join,
    18  	"title":    strings.Title,
    19  	"lower":    strings.ToLower,
    20  	"upper":    strings.ToUpper,
    21  	"pad":      padWithSpace,
    22  	"truncate": truncateWithLength,
    23  }
    24  
    25  // Parse creates a new anonymous template with the basic functions
    26  // and parses the given format.
    27  func Parse(format string) (*template.Template, error) {
    28  	return NewParse("", format)
    29  }
    30  
    31  // NewParse creates a new tagged template with the basic functions
    32  // and parses the given format.
    33  func NewParse(tag, format string) (*template.Template, error) {
    34  	return template.New(tag).Funcs(basicFunctions).Parse(format)
    35  }
    36  
    37  // padWithSpace adds whitespace to the input if the input is non-empty
    38  func padWithSpace(source string, prefix, suffix int) string {
    39  	if source == "" {
    40  		return source
    41  	}
    42  	return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
    43  }
    44  
    45  // truncateWithLength truncates the source string up to the length provided by the input
    46  func truncateWithLength(source string, length int) string {
    47  	if len(source) < length {
    48  		return source
    49  	}
    50  	return source[:length]
    51  }