Advertisement
krovn

Untitled

Nov 15th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.96 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "html/template"
  5.     "log"
  6.     "net/http"
  7. )
  8.  
  9. var tpl *template.Template
  10.  
  11. var funkcijas = template.FuncMap{
  12.     "dbl": double,
  13.     "add": add,
  14. }
  15.  
  16. type person struct {
  17.     Name string
  18.     Age  int
  19. }
  20.  
  21. func double(x int) int {
  22.     return x * 2
  23. }
  24. func add(x int) int {
  25.     return x + 2
  26. }
  27.  
  28. func init() {
  29.     tpl = template.Must(template.New("").Funcs(funkcijas).ParseFiles("templates/two.gohtml"))
  30. }
  31.  
  32. func main() {
  33.     http.HandleFunc("/", index)
  34.     http.ListenAndServe(":8080", nil)
  35. }
  36.  
  37. func index(res http.ResponseWriter, req *http.Request) {
  38.     user1 := person{
  39.         Name: "janis",
  40.         Age:  24,
  41.     }
  42.     user2 := person{
  43.         Name: "Edgars",
  44.         Age:  27,
  45.     }
  46.     user := []person{user1, user2}
  47.     err := tpl.ExecuteTemplate(res, "two.gohtml", user)
  48.     if err != nil {
  49.         log.Fatalln(err)
  50.     }
  51. }
  52.  
  53.  
  54. <body>
  55.     Home of two.gohtml<br /><br />
  56.     {{range .}}
  57.         {{.Name}} - {{.Age}}<br />
  58.         {{dbl .Age}}
  59.         {{add .Age}}<br /><br />
  60.     {{end}}
  61. </body>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement