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
-> <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 can I use my function in multiple templates? Is the answer to this question here on so the only way to go?
- Is this the correct approach? Remember, I'd like to change the text on some strings, similar to the title example in the documentation (http://golang.org/pkg/text/template/#FuncMap - Example (Func))?
-
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) }