duanhui4160
2018-12-13 07:58
浏览 47
已采纳

如何使template.Execute()写入文件而不是response.Writer?

I have a below code to parse the template file and write the parsed html to ResponseWriter:-

package main

import (
    "net/http"
    "html/template"
)

func handler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("view.html")
    t.Execute(w, "Hello World!")
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/view", handler)
    server.ListenAndServe()
}  

and the template file "template.html" is as:

<html>
<head>
    <title>First Program</title>
</head>
<body>
    {{ . }}
</body>
</html>  

Now, Instead of writing parsed/executed file to ResponseWriter, I would like to write those contents to html file say "parsed.html". How can I achieve it. I'm new to Go, so having hard time getting the idea. Thank you.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxing1353 2018-12-13 08:21
    已采纳

    Here's one way to do it:

    t, err := template.ParseFiles("view.html")
    if err != nil {
        // handle error
    }
    
    // Create the file
    f, err := os.Create("parsed.html")
    if err != nil {
        // handle error
    }
    
    // Execute the template to the file.
    err = t.Execute(f, "Hello World!")
    if err != nil {
        // handle error
    }
    
    // Close the file when done.
    f.Close()
    

    Run it on the playground

    Key Point: An *os.File and an http.ResponseWriter both satisfy the io.Writer interface used in the first argument to Execute.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题