Answer the question
In order to leave comments, you need to log in
How to pass the parsed Template to the html file writing function?
Hello. The createIndexFile function creates an html file and writes data to it, but I can’t pass the value from t.ExecuteTemplate to this function, can anyone know how to implement this?
writePost (path string){
t, err := template.ParseFiles("/root/go/templates/site/tape/index.html", "/root/go/templates/site/tape/header.html", " /root/go/templates/site/tape/footer.html")
if err != nil {
writeError(err)
return 0
}
var data io.Writer
t.ExecuteTemplate(data, "index", Data)
createIndexFile(path, data, 0644, uig, gid) // Function to write html file
}
Answer the question
In order to leave comments, you need to log in
You need to pass a ready-made Writer to the ExecuteTemplate function. That is, first open the file, then call ExecuteTemplate.
package main
import (
"html/template"
"log"
"os"
)
type Data struct {
Text string
}
func main() {
t := template.Must(template.New("index").Parse(`Some template code. Text: {{.Text}}`))
file, err := os.Create("outfile.htm")
if err != nil {
log.Fatal("Cannot create file: ", err)
}
defer file.Close()
t.ExecuteTemplate(file, "index", Data{Text: "Hello"})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question