github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/tplx/tpl_demo1.go (about) 1 package tplx 2 3 import ( 4 "html" 5 tt "html/template" 6 "net/http" 7 8 "github.com/pbberlin/tools/net/http/loghttp" 9 ) 10 11 // preconceive all embedded templates: 12 const T0 = ` 13 T0 <br> 14 <span style='color:#aaf; line-height:200%;display:inline-block; margin:8px; margin-left:120px; border: 1px solid #aaf'> 15 {{template "T1" .}} 16 </span> 17 <hr> 18 ` 19 20 const T1 = ` 21 {{define "T1"}} 22 T1 <br> 23 --{{if .key1}}{{.key1}}{{else}}no dyn data{{end}}--<br> 24 <span style='min-width:200px;color:#faa; display:inline-block; margin:8px; margin-left:120px; border: 1px solid #faa'> 25 {{template "T2" .key2 }} 26 </span> 27 28 {{end}} 29 ` 30 31 const iterOver = `{{ $mapOrArray := . }} 32 {{range $index, $element := $mapOrArray }} 33 <li><strong>$index</strong>: $element </li> 34 {{end}}` 35 36 const treatFirstIterDifferent = `{{if $index}},x{{end}}` 37 38 func templatesCompileDemo(w http.ResponseWriter, r *http.Request, m map[string]interface{}) { 39 40 w.Header().Set("Content-Type", "text/html") 41 42 funcMap := tt.FuncMap{ 43 "unescape": html.UnescapeString, 44 "escape": html.EscapeString, 45 } 46 47 var t_base *tt.Template 48 var err error = nil 49 50 // creating T0 - naming it - adding func map 51 t_base = tt.Must(tt.New("str_T0_outmost").Funcs(funcMap).Parse(T0)) 52 loghttp.E(w, r, err, false) 53 54 // adding the definition of T1 - introducing reference to T2 - undefined yet 55 t_base, err = t_base.Parse(T1) // definitions must appear at top level - but not at the start 56 loghttp.E(w, r, err, false) 57 58 // create two clones 59 // now both containing T0 and T1 60 tc_1, err := t_base.Clone() 61 loghttp.E(w, r, err, false) 62 tc_2, err := t_base.Clone() 63 loghttp.E(w, r, err, false) 64 65 // adding different T2 definitions 66 s_if := "{{if .}}{{.}}{{else}}no dyn data{{end}}" 67 tc_1, err = tc_1.Parse("{{define `T2`}}T2-A <br>--" + s_if + "-- {{end}}") 68 loghttp.E(w, r, err, false) 69 tc_2, err = tc_2.Parse("{{define `T2`}}T2-B <br>--" + s_if + "-- {{end}}") 70 loghttp.E(w, r, err, false) 71 72 // writing both clones to the response writer 73 err = tc_1.ExecuteTemplate(w, "str_T0_outmost", nil) 74 loghttp.E(w, r, err, false) 75 76 // second clone is written with dynamic data on two levels 77 dyndata := map[string]string{"key1": "dyn val 1", "key2": "dyn val 2"} 78 err = tc_2.ExecuteTemplate(w, "str_T0_outmost", dyndata) 79 loghttp.E(w, r, err, false) 80 81 // Note: it is important to pass the DOT 82 // {{template "T1" .}} 83 // {{template "T2" .key2 }} 84 // ^ 85 // otherwise "dyndata" can not be accessed by the inner templates... 86 87 // leaving T2 undefined => error 88 tc_3, err := t_base.Clone() 89 loghttp.E(w, r, err, false) 90 err = tc_3.ExecuteTemplate(w, "str_T0_outmost", dyndata) 91 // NOT logging the error: 92 // loghttp.E(w, r, err, false) 93 94 }