英文:
Execute template to file
问题
我有一个名为template.html的模板文件,内容如下:
你好{{.Name}},欢迎!
还有以下代码:
import (
"fmt"
"text/template"
)
func main() {
type person struct {
Name string
}
p := &person{"clinyong"}
t := template.Must(template.New("template.html").ParseFiles("template.html"))
f, err := os.OpenFile("test", os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
err := t.Execute(f, p)
if err != nil {
fmt.Println(err)
}
}
在t.Execute(f, p)中出现了一个错误,提示f是一个坏的文件描述符。
像上面展示的那样,执行模板并将输出写入文件是可能的吗?我看到一些示例中,Execute中的f几乎都是http.ResponseWriter或os.Stdout。
英文:
I have a template file template.html as follow
Hello {{.Name}}, welcome!
and the code
import (
"fmt"
"text/template"
)
func main() {
type person struct {
Name string
}
p := &person{"clinyong"}
t := template.Must(template.New("template.html").ParseFiles("template.html"))
f, err := os.OpenFile("test", os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
err := t.Execute(f, p)
if err != nil {
fmt.Println(err)
}
}
t.Execute(f, p) calls a error, saying that f is a bad file descriptor.
Is it possible to execute a template output to a file as shown above? I see some examples, the f in Execute is almost http.ResponseWriter or os.Stdout.
答案1
得分: 3
如@TimCooper所说,我需要在os.OpenFile中包含os.O_WRONLY。
英文:
As @TimCooper said, I need to include os.O_WRONLY in os.OpenFile.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论