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

标签 go go-templates

我有下面的代码来解析模板文件并将解析后的 html 写入 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()
}  

模板文件“template.html”如下:

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

现在,我不想将解析/执行的文件写入 ResponseWriter,而是将这些内容写入 html 文件,比如“parsed.html”。我怎样才能实现它。我是 Go 的新手,所以很难理解。谢谢。

最佳答案

这是一种方法:

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

要点:*os.File 和 http.ResponseWriter 都满足 Execute 的第一个参数中使用的 io.Writer 接口(interface)。

关于go - 如何使 template.Execute() 写入文件而不是 response.Writer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757331/

相关文章:

templates - Go Template ParseFiles 函数解析多个文件

go - 在模板中访问数组中的任意元素

go - 将字符串解析为特定类型的 int(int8、int16、int32、int64)

go - 无法命名包 “documentation”

html - Golang HTML Web Apps 中没有这样的模板 "xxx"

go - 如何使模板与 gin 框架一起工作?

if-statement - 如何在HTML属性中插入if语句?

pointers - 简洁的 nil 检查结构字段指针?

go - 尝试使用 interface{} slice 来选择随机元素

go - 在 Windows 中安装 Go 的问题