2016-03-04 17:29:44 +00:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"strings"
|
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
|
|
|
// basicFunctions are the set of initial
|
|
|
|
// functions provided to every template.
|
|
|
|
var basicFunctions = template.FuncMap{
|
|
|
|
"json": func(v interface{}) string {
|
|
|
|
a, _ := json.Marshal(v)
|
|
|
|
return string(a)
|
|
|
|
},
|
2017-01-26 20:49:40 +00:00
|
|
|
"split": strings.Split,
|
|
|
|
"join": strings.Join,
|
|
|
|
"title": strings.Title,
|
|
|
|
"lower": strings.ToLower,
|
|
|
|
"upper": strings.ToUpper,
|
|
|
|
"pad": padWithSpace,
|
|
|
|
"truncate": truncateWithLength,
|
2016-03-04 17:29:44 +00:00
|
|
|
}
|
|
|
|
|
2017-01-17 04:45:27 +00:00
|
|
|
// Parse creates a new anonymous template with the basic functions
|
2016-03-04 17:29:44 +00:00
|
|
|
// and parses the given format.
|
|
|
|
func Parse(format string) (*template.Template, error) {
|
|
|
|
return NewParse("", format)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewParse creates a new tagged template with the basic functions
|
|
|
|
// and parses the given format.
|
|
|
|
func NewParse(tag, format string) (*template.Template, error) {
|
|
|
|
return template.New(tag).Funcs(basicFunctions).Parse(format)
|
|
|
|
}
|
2016-09-13 18:21:07 +00:00
|
|
|
|
|
|
|
// padWithSpace adds whitespace to the input if the input is non-empty
|
|
|
|
func padWithSpace(source string, prefix, suffix int) string {
|
|
|
|
if source == "" {
|
|
|
|
return source
|
|
|
|
}
|
|
|
|
return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
|
|
|
|
}
|
2017-01-26 20:49:40 +00:00
|
|
|
|
|
|
|
// truncateWithLength truncates the source string up to the length provided by the input
|
|
|
|
func truncateWithLength(source string, length int) string {
|
|
|
|
if len(source) < length {
|
|
|
|
return source
|
|
|
|
}
|
|
|
|
return source[:length]
|
|
|
|
}
|