Upgrade to Pro — share decks privately, control downloads, hide ads and more …

3 Things You May Not Know About The Go Template...

3 Things You May Not Know About The Go Template Engine

A short introduction to the Go template engine

Sau Sheong Chang

March 03, 2015
Tweet

More Decks by Sau Sheong Chang

Other Decks in Technology

Transcript

  1. 3  Things  You  May  Not   Know  About  The  Go

      Template  Engine   Chang  Sau  Sheong   Feb  2015  
  2. Where’s  Go  template  engine?   Logic-­‐less   Go   template

      engine   Embedded   logic   Mustache,  Handlebars  etc   JSP,  Haml,  Jade  etc  
  3. package main import ( "net/http" "html/template" ) func process(w http.ResponseWriter,

    r *http.Request) { t, _ := template.ParseFiles("tmpl.html") t.Execute(w, "Hello World!") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } http.HandleFunc("/process", process) server.ListenAndServe() }
  4. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/ html; charset=utf-8"> <title>Go

    Web Programming</title> </head> <body> {{ 12.3456 | printf "%.2f" }} </body> </html>
  5. func formatDate(t time.Time) string { layout := "2006-01-02" return t.Format(layout)

    } func process(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap { "fdate": formatDate } t := template.New("tmpl.html").Funcs(funcMap) t, _ = t.ParseFiles("tmpl.html") t.Execute(w, time.Now()) }
  6. func process(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("tmpl.html")

    content := `I asked: <i>"What's up?"</i>` t.Execute(w, content) }
  7. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Go Web Programming</title> </head>

    <body> <div>{{ . }}</div> <div><a href="/{{ . }}">Path</a></div> <div><a href="/?q={{ . }}">Query</a></div> <div><a onclick="f('{{ . }}')">Onclick</a></div> </body> </html>
  8. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Go Web Programming</title> </head>

    <body> <div>I asked: &lt;i&gt;&#34;What&#39;s up?&#34;&lt;/ i&gt;</div> <div><a href="/I%20asked:%20%3ci%3e%22What%27s%20up? %22%3c/i%3e">Path</a></div> <div><a href="/?q=I%20asked%3a%20%3ci%3e%22What%27s %20up%3f%22%3c%2fi%3e">Query</a></div> <div><a onclick="f('I asked: \x3ci\x3e\x22What\x27s up?\x22\x3c\/i\x3e')">Onclick</a></div> </body> </html>
  9. Context Content Original text I asked: <i>"What's up?"</i> {{ .

    }} I asked: &lt;i&gt;&#34;What&#39;s up?&#34;&lt;/i&gt; <a href="/{{ . }}"> I%20asked:%20%3ci%3e%22What%27s%20up?%22%3c/i%3e <a href="/?q={{ . }}"> I%20asked%3a%20%3ci%3e%22What%27s%20up%3f%22%3c %2fi%3e <a onclick="{{ . }}"> I asked: \x3ci\x3e\x22What\x27s up?\x22\x3c\/i\x3e