我有下面的代码来解析模板文件并将解析后的 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()
要点:*os.File 和 http.ResponseWriter 都满足 Execute 的第一个参数中使用的 io.Writer 接口(interface)。
关于go - 如何使 template.Execute() 写入文件而不是 response.Writer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757331/