Answers for "golang render template"

Go
0

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)
}
Posted by: Guest on April-17-2021
0

golang template

package main

import (
	"html/template"
	"net/http"
	"path"
)

func main() {
	dir := path.Join("index.html")
	html, err := template.ParseFiles(dir)

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("assets"))))
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {

		if err != nil {
			http.Error(rw, "parse file error", 400)
			return
		}

		content := map[string]string{"name": "john doe"}

		err = html.Execute(rw, content)

		if err != nil {
			http.Error(rw, "render file error", 400)
			return
		}

	})

	http.ListenAndServe(":3000", nil)
}
Posted by: Guest on September-30-2021

Code answers related to "golang render template"

Browse Popular Code Answers by Language