How to include and execute HTML template?
Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.
Execute applies a parsed template to the specified data object, writing the output to w. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.
Create test.html with below content:
Golang Template Example
Template Testing
Country is {{.Country}}
City is {{.City}}
Example
package main
import (
"fmt"
"html/template"
"net/http"
)
const (
Port = ":8080"
)
func serveStatic(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("test.html")
if err != nil {
fmt.Println(err)
}
items := struct {
Country string
City string
}{
Country: "Australia",
City: "Paris",
}
t.Execute(w, items)
}
func main() {
http.HandleFunc("/",serveStatic)
http.ListenAndServe(Port, nil)
}
Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/golayrva/public_html/lib/Varien/Filter/Template/Tokenizer/Abstract.php on line 89
Now run url :http://localhost:8080/ in your browser and see the below content
Most Helpful This Week
Example: Stack and Caller from RUNTIME package
How can I convert a string variable into Boolean, Integer or Float type in Golang?
How pointer & and * and ** works in Golang?
Example to use Weekday and YearDay function
How to copy a map to another map?
Golang download image from given URL
Example: ReadAll, ReadDir, and ReadFile from IO Package
How to check if a map contains a key in Go?
The return values of a function can be named in Golang
How to use array in Go Programming Language?