Reputation: 17345
The Goal: using multiple templates in an HTTP server where I want to change newlines into <br/>
tags on some strings.
A stripped down example:
I have two templates a.tmpl
and b.tmpl
which look like this:
Template a {{dosomething}}
(and similar the other template). Both reside in a directory called templates
. I believe that I need to create a function to do the \n
-> <br />
replacement (dosomething
above).
This is my (non working) sample code:
package main
import (
"log"
"text/template"
)
func main() {
// funcMap := template.FuncMap{
// "dosomething": func() string { return "done something" },
// }
templates, err := template.ParseGlob("templates/*.tmpl")
if err != nil {
log.Fatal(err)
}
log.Printf("%#v", templates)
}
The error message is:
2013/03/04 20:08:19 template: a.tmpl:1: function "dosomething" not defined
exit status 1
which makes sense, because during the parsing time, the function dosomething
is not known.
How do I access b.tmpl
in the following code:
package main
import (
"log"
"text/template"
)
func main() {
funcMap := template.FuncMap{
"dosomething": func() string { return "done something" },
}
t, err := template.New("a.tmpl").Funcs(funcMap).ParseGlob("templates/*.tmpl")
if err != nil {
log.Fatal(err)
}
log.Printf("%#v", t)
}
Upvotes: 4
Views: 4239
Reputation: 16110
Your last snippet of code looks about right to me.
To render b.tmpl, just call
t.ExecuteTemplate(w, "b.tmpl", data)
You can access a.tmpl the same way; I would recommend doing this for consistency, rather than setting the name to "a.tmpl" in the call to New.
Upvotes: 3