Skip to content

Commit

Permalink
Add from string templates with functions (#4)
Browse files Browse the repository at this point in the history
This enable adding multitemplates using strings and passing custom functions to them.

This is useful specially when working with embeded resources managers like go-bindata.
  • Loading branch information
Victor Castell authored and appleboy committed Jun 20, 2017
1 parent 7d1ec4f commit 753bf91
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
12 changes: 12 additions & 0 deletions multitemplate.go
Expand Up @@ -49,6 +49,18 @@ func (r *Render) AddFromString(name, templateString string) *template.Template {
return tmpl
}

// AddFromStringsFuncs supply add template from strings
func (r *Render) AddFromStringsFuncs(name string, funcMap template.FuncMap, templateStrings ...string) *template.Template {
tmpl := template.New(name).Funcs(funcMap)

for _, ts := range templateStrings {
tmpl = template.Must(tmpl.Parse(ts))
}

r.Add(name, tmpl)
return tmpl
}

// AddFromFilesFuncs supply add template from file callback func
func (r Render) AddFromFilesFuncs(name string, funcMap template.FuncMap, files ...string) *template.Template {
tname := filepath.Base(files[0])
Expand Down
21 changes: 21 additions & 0 deletions multitemplate_test.go
Expand Up @@ -38,6 +38,13 @@ func createFromString() Render {
return r
}

func createFromStringsWithFuncs() Render {
r := New()
r.AddFromStringsFuncs("index", template.FuncMap{}, `Welcome to {{ .name }} {{template "content"}}`, `{{define "content"}}template{{end}}`)

return r
}

func TestMissingTemplateOrName(t *testing.T) {
r := New()
tmpl := template.Must(template.New("test").Parse("Welcome to {{ .name }} template"))
Expand Down Expand Up @@ -91,3 +98,17 @@ func TestAddFromString(t *testing.T) {
assert.Equal(t, 200, w.Code)
assert.Equal(t, "Welcome to index template", w.Body.String())
}

func TestAddFromStringsFruncs(t *testing.T) {
router := gin.New()
router.HTMLRender = createFromStringsWithFuncs()
router.GET("/", func(c *gin.Context) {
c.HTML(200, "index", gin.H{
"name": "index",
})
})

w := performRequest(router, "GET", "/")
assert.Equal(t, 200, w.Code)
assert.Equal(t, "Welcome to index template", w.Body.String())
}

0 comments on commit 753bf91

Please sign in to comment.