Fragment Description:



Go html/template.
Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.
Here the template 'page' is in a variable, usually it is written in a file.
And in that case, the content of the file is read and cached...
in a variable :) Execute this program and then try:
'curl -i localhost:8082/' (inspired by Alex Edwards snippets.

httpRenderingHTMLTemplate

Last update, on 2015, Fri 9 Oct, 16:15:39

/* ... <== see fragment description ... */

package main

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

type Data struct {
    Name    string
    Hobbies []string
}

var tpl = `<h1>Hello from: {{ .Name }}</h1>
<hr>
<h3>Your hobbies are:</h3>
{{$Hobbies := .Hobbies }}
{{range $i, $hobby := $Hobbies}}
<h4>Item [{{ $i }}]: {{ $hobby }}</h4>
{{end}}
<hr>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
`

func main() {
    http.HandleFunc("/", foo)
    fmt.Println("Listening on port: 8082....")
    http.ListenAndServe("localhost:8082", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
    data := &Data{"Go Fragments", []string{"snowboarding", "programming"}}
    // step1
    tmpl, err := template.New("tpl").Parse(tpl)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // step2
    if err := tmpl.Execute(w, *data); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}



Comments