Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.25 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "html/template"
  5.     "net/http"
  6. )
  7.  
  8. var tpl *template.Template
  9.  
  10. var funkcijas = template.FuncMap{
  11.     "addt": addthree,
  12.     "timt": timesthree,
  13. }
  14.  
  15. func addthree(x int) int   { return x + 3 }
  16. func timesthree(x int) int { return x * 3 }
  17.  
  18. func init() {
  19.     tpl = template.Must(template.New("").Funcs(funkcijas).ParseGlob("templates/*.gohtml"))
  20. }
  21.  
  22. type person struct {
  23.     Name string
  24.     Age  int
  25. }
  26.  
  27. func (p person) AgeDbl() int   { return p.Age * 2 }
  28. func (p person) Div(x int) int { return x / 2 }
  29. func (p person) Add(x int) int { return x + 5 }
  30.  
  31. func main() {
  32.     http.HandleFunc("/", one)
  33.     http.Handle("/favicon.ico", http.NotFoundHandler())
  34.     http.ListenAndServe(":8080", nil)
  35. }
  36.  
  37. func one(res http.ResponseWriter, req *http.Request) {
  38.     user1 := person{Name: "Edgars", Age: 26}
  39.     user2 := person{Name: "Martins", Age: 29}
  40.     users := []person{user1, user2}
  41.     tpl.ExecuteTemplate(res, "one.gohtml", users)
  42. }
  43. ========================
  44. <html>
  45. <body>
  46.     {{range .}}
  47.         <b>{{.Age}}-{{.Name}}<br></b>
  48.         {{.AgeDbl}} -> {{.AgeDbl|.Div}}<br>
  49.         {{.Age|.Div}} -> {{.Age|.Div|.Add}}<br>
  50.         {{.Age|.Div|.Add|addt}} -> {{.Age|.Div|.Add|addt|timt}}<br>
  51.         {{addt .Age}} -> {{addt .Age|timt}} -> {{addt .Age|timt|.Div}}<br><br>
  52.     {{end}}
  53. </body>
  54. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement