template: Use zero-values for missing values.

Currently missing values will get the value <no value>
rather than the empty string. Using the empty string is
more consistent, and should be easier for users to deal with too.
This commit is contained in:
Brian Brazil 2015-11-28 13:45:32 +00:00
parent aa5b35ed94
commit 738af32057
2 changed files with 17 additions and 0 deletions

View file

@ -273,6 +273,7 @@ func (te Expander) Expand() (result string, resultErr error) {
}()
tmpl, err := text_template.New(te.name).Funcs(te.funcMap).Parse(te.text)
tmpl.Option("missingkey=zero")
if err != nil {
return "", fmt.Errorf("error parsing template %v: %v", te.name, err)
}
@ -297,6 +298,7 @@ func (te Expander) ExpandHTML(templateFiles []string) (result string, resultErr
}()
tmpl := html_template.New(te.name).Funcs(html_template.FuncMap(te.funcMap))
tmpl.Option("missingkey=zero")
tmpl.Funcs(html_template.FuncMap{
"tmpl": func(name string, data interface{}) (html_template.HTML, error) {
var buffer bytes.Buffer

View file

@ -84,6 +84,21 @@ func TestTemplateExpansion(t *testing.T) {
text: "{{ query \"metric{instance='a'}\" | first | label \"instance\" }}",
output: "a",
},
{
// Missing label is empty when using label function.
text: "{{ query \"metric{instance='a'}\" | first | label \"foo\" }}",
output: "",
},
{
// Missing label is empty when not using label function.
text: "{{ $x := query \"metric\" | first }}{{ $x.Labels.foo }}",
output: "",
},
{
text: "{{ $x := query \"metric\" | first }}{{ $x.Labels.foo }}",
output: "",
html: true,
},
{
// Range over query and sort by label.
text: "{{ range query \"metric\" | sortByLabel \"instance\" }}{{.Labels.instance}}:{{.Value}}: {{end}}",