krovn

Untitled

Nov 15th, 2018
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.21 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "html/template"
  5.     "net/http"
  6. )
  7.  
  8. type person struct {
  9.     Name  string
  10.     Age   int
  11.     Admin bool
  12. }
  13.  
  14. var tpl *template.Template
  15.  
  16. func init() {
  17.     tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
  18. }
  19.  
  20. func main() {
  21.     http.HandleFunc("/", index)
  22.     http.ListenAndServe(":8080", nil)
  23. }
  24.  
  25. func index(res http.ResponseWriter, req *http.Request) {
  26.     p1 := person{
  27.         Name:  "Janis",
  28.         Age:   24,
  29.         Admin: false,
  30.     }
  31.     p2 := person{
  32.         Name:  "",
  33.         Age:   27,
  34.         Admin: true,
  35.     }
  36.     p3 := person{
  37.         Name:  "Edgars",
  38.         Age:   23,
  39.         Admin: false,
  40.     }
  41.     persons := []person{p1, p2, p3}
  42.     tpl.ExecuteTemplate(res, "two.gohtml", persons)
  43. }
  44.  
  45. /*
  46. ____one.gohtml
  47. {{define "polar"}}
  48. text from one.gohtml
  49. {{end}}
  50. ____two.gothml
  51. <body>
  52.     This might be two.gohtml? But I am not sure.
  53.     <h3>
  54.         {{range .}}
  55.             {{.}}
  56.         {{end}}
  57.         <br />
  58.         {{range .}}
  59.             {{if .Name}}
  60.                 {{.Name}}
  61.             {{end}}
  62.         {{end}}
  63.         <br />
  64.         {{range .}}
  65.             {{if and .Name .Age}}
  66.                 {{.Name}} --- {{.Age}} --- {{.Admin}} ,
  67.             {{end}}
  68.         {{end}}
  69.     </h3>
  70.         {{template "polar"}}
  71. </body>
  72. */
Advertisement
Add Comment
Please, Sign In to add comment