golang html template code example

Example 1: golang render html template

// parse html via index.html

package main

import (
	"net/http"
	"text/template"
)

type Context struct {
	Title  string
	Name   string
	Fruits [3]string
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Content Type", "text/html")
		templates, _ := template.New("doc").ParseFiles("index.html")
		context := Context{
			Title:  "My Fruits",
			Name:   "John",
			Fruits: [3]string{"Apple", "Lemon", "Orange"},
		}
		templates.Execute(w, context)
	})
	http.ListenAndServe(":8000", nil)
}

Example 2: golang render html template

// parser html via variable

package main

import (
	"net/http"
	"text/template"
)

type Context struct {
	Title  string
	Name   string
	Fruits [3]string
}

func main() {
	const doc = `
<!DOCTYPE html>
<html>
    <head>
        {{.Title}}
    </head>
    <body>
        <h3>Hi, {{.Name}}. The fruits are:</h3>
        <ul>
            {{range .Fruit}}
                <li>{{.}}</li>
            {{end}}
        </ul>
    </body>
</html>
`

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Content Type", "text/html")
		templates, _ := template.New("doc").Parse(doc)
		context := Context{
			Title:  "My Fruits",
			Name:   "John",
			Fruits: [3]string{"Apple", "Lemon", "Orange"},
		}
		templates.Lookup("doc").Execute(w, context)
	})
	http.ListenAndServe(":8000", nil)
}

Tags:

Go Example