Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ var HeaderFunctions = template.FuncMap{
},
}

// aliases for convenience
var aliases = map[string]string{
"json": "{{json .}}",
}

// Parse creates a new anonymous template with the basic functions
// and parses the given format.
func Parse(format string) (*template.Template, error) {
Expand All @@ -76,6 +81,9 @@ func New(tag string) *template.Template {
// NewParse creates a new tagged template with the basic functions
// and parses the given format.
func NewParse(tag, format string) (*template.Template, error) {
if alias, ok := aliases[format]; ok {
format = alias
}
return New(tag).Parse(format)
}

Expand Down
20 changes: 20 additions & 0 deletions templates/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ func TestNewParse(t *testing.T) {
assert.Check(t, is.Equal(want, b.String()))
}

func TestParseJSON(t *testing.T) {
f := func(t testing.TB, format string) {
tm, err := Parse(format)
assert.NilError(t, err)
var b bytes.Buffer
m := map[string]int{
"foo": 42,
}
assert.NilError(t, tm.Execute(&b, m))
want := `{"foo":42}`
assert.Check(t, is.Equal(want, b.String()))
}
t.Run("CanonicalForm", func(t *testing.T) {
f(t, "{{json .}}")
})
t.Run("ConvenienceForm", func(t *testing.T) {
f(t, "json")
})
}

func TestParseTruncateFunction(t *testing.T) {
source := "tupx5xzf6hvsrhnruz5cr8gwp"

Expand Down