Purpose: using multiple templates on an HTTP server, where I want to change newline characters to <br/> tags for some lines.
Truncated example:
I have two templates a.tmpl and b.tmpl that look like this:
Template a {{dosomething}}
(and similar other template). Both are in a directory called templates . I believe that I need to create a function to replace \n → <br /> ( dosomething above).
This is my (non-working) code example:
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) }
Error message:
2013/03/04 20:08:19 template: a.tmpl:1: function "dosomething" not defined exit status 1
which makes sense since the dosomething function dosomething unknown during parsing.
- How can I use my function in multiple templates? Is the answer to this question here, so what is the only way to go?
- Is this the right approach? Remember that I would like to change the text to some lines, similar to the example header 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) }
source share