topskip
topskip

Reputation: 17345

Multiple templates with FuncMap

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.

  1. How can I use my function in multiple templates? Is the answer to this question here on so the only way to go?
  2. 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))?
  3. 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

Answers (1)

andybalholm
andybalholm

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

Related Questions