2018-12-13 07:58
浏览 52


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

package main

import (

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

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

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

    <title>First Program</title>
    {{ . }}

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.

    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题