golang render html template
To render an HTML template in Go using the html/template
package, you can follow these steps:
- Import the required packages:
import (
"html/template"
"os"
)
The html/template
package provides functionality to render HTML templates, while the os
package allows you to write the output to a file or any other io.Writer
.
- Create the template:
tpl, err := template.New("mytemplate").ParseFiles("template.html")
This code creates a new template named "mytemplate" and parses the contents of the template.html
file. It returns a template object tpl
and an error err
.
- Define the data to be passed to the template:
data := struct {
Name string
}{
Name: "John Doe",
}
Here, a struct is defined with a field Name
of type string. This struct represents the data that will be passed to the template.
- Execute the template:
err = tpl.Execute(os.Stdout, data)
The Execute
method executes the template, writing the output to the specified io.Writer
. In this example, the output is written to the standard output (os.Stdout
), but you can provide any other io.Writer
such as a file or a network connection.
- Handling errors:
if err != nil {
// Handle the error
}
After executing the template, you should check if any errors occurred during the execution and handle them accordingly.
By following these steps, you can render an HTML template in Go using the html/template
package.