How to use go template to parse html files with FuncMap
Asked Answered
K

1

2

I use following code to parse html template. It works well.

func test(w http.ResponseWriter, req *http.Request) {

    data := struct {A int B int }{A: 2, B: 3}

    t := template.New("test.html").Funcs(template.FuncMap{"add": add})

    t, err := t.ParseFiles("test.html")

    if err!=nil{
        log.Println(err)
    }
    t.Execute(w, data)
}

func add(a, b int) int {
    return a + b
}

and html template test.html.

<html>
<head>
    <title></title>
</head>
<body>
    <input type="text" value="{{add .A .B}}">
</body>
</html>

But when I move html file to another directory. Then use the following code. The output is always empty.

t := template.New("./templates/test.html").Funcs(template.FuncMap{"add": add})

t, err := t.ParseFiles("./templates/test.html")

Can anyone tell me what's wrong? Or html/template package can not be used like this?

Kinsey answered 3/12, 2015 at 5:50 Comment(0)
O
2

What's wrong is that your program (the html/template package) can't find the test.html file. When you specify relative paths (yours are relative), they are resolved to the current working directory.

You have to make sure the html files/templates are in the right place. If you start your app with go run ... for example, relative paths are resolved to the folder you're in, that will be the working directory.

This relative path: "./templates/test.html" will try to parse the file being in the templates subfolder of the current folder. Make sure it's there.

Another option is to use absolute paths.

And also another important note: Do not parse templates in your handler function! That runs to serve each incoming request. Instead parse them in the package init() functions once.

More details on this:

It takes too much time when using "template" package to generate a dynamic web page to client in golang

Outwash answered 3/12, 2015 at 7:1 Comment(1)
Sorry for this stupid question. Because I mixed the parameter of template.New(name string) and t.ParseFiles(filenames...string). It should be template.New(filename string).Kinsey

© 2022 - 2024 — McMap. All rights reserved.