I'm trying to parse CSS files in which variables can be injected that are defined in a config file. Currently the function does:
func parse(path string) {
f, err := ioutil.ReadFile(path)
if err != nil {
log.Print(err)
return
}
// Parse requires a string
t, err := template.New("css").Parse(string(f))
if err != nil {
log.Print(err)
return
}
// A sample config
config := map[string]string {
"textColor": "#abcdef",
"linkColorHover": "#ffaacc",
}
// Execute needs some sort of io.Writer
err = t.Execute(os.Stdout, config)
if err != nil {
log.Print("Can't execute ", path)
}
}
My problem is that template.Parse()
requires the content as string and template.Execute()
an io.Writer
as argument. I tried to open the file with os.Open()
which returns a file object that implements the io.Writer
interface. But how can I get the file's content as a string from such a file object in order to use it with Parse()
?
Open Word Template Files To open a Word template file, which contains a template library, right-click the default. dotx file name and select Open.
Go templates are a powerful method to customize output however you want, whether you're creating a web page, sending an e-mail, working with Buffalo, Go-Hugo, or just using some CLI such as kubectl. There're two packages operating with templates — text/template and html/template .
Golang Templates ParseFile and Execute In the render template Function first, the student struct is initialized with values. The Template is then parsed using the ParseFile() function from the html/template package. This creates a new template and parses the filename that is passed as input.
Use ParseFiles to parse the template. This code basically does the same thing as calling ReadFile, template.New and Parse as in the question, but it's shorter.
t, err := template.ParseFiles(path)
if err != nil {
log.Print(err)
return
}
Use os.Create to open the output file.
f, err := os.Create(path)
if err != nil {
log.Println("create file: ", err)
return
}
A file is an io.Writer. You can execute the template directly to the open file:
err = t.Execute(f, config)
if err != nil {
log.Print("execute: ", err)
return
}
Close the file when done.
f.Close()
Complete working example on the playground.
Here is a function I made with Cerise Limón's answer
func createFileUsingTemplate(t *template.Template, filename string, data interface{}) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
err = t.Execute(f, data)
if err != nil {
return err
}
return nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With