Golang笔记

理解golang template 的渲染过程

理解golang template 的渲染过程

golang template

方法1:

package main

import (
    "net/http"
    "html/template"
)

func handler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("view.html") //setp 1
    t.Execute(w, "Hello World!") //step 2
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/view", handler)
    server.ListenAndServe()
}

html

<html>
<head>
    <title>First Program</title>
</head>
<body>
    {{ . }}
</body>
</html>

方法2:

package main

import (
  "html/template"
  "net/http"
)

var tmpl = `<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    {{ . }}
</body>
</html>
`
func handler(w http.ResponseWriter, r *http.Request) {
  t := template.New("main") //name of the template is main
  t, _ = t.Parse(tmpl) // parsing of template string
  t.Execute(w, "Hello World!")
}

func main() {
  server := http.Server{
    Addr: "127.0.0.1:8080",
  }
  http.HandleFunc("/view", handler)
  server.ListenAndServe()
}

方法3:

package main
import (
  "net/http"
  "html/template"
)

func handler1(w http.ResponseWriter, r *http.Request) {
  t, _ := template.ParseFiles("t1.html", "t2.html") 
  t.Execute(w, "Asit")
}

func handler2(w http.ResponseWriter, r *http.Request) {
  t, _ := template.ParseFiles("t1.html", "t2.html") 
  t.ExecuteTemplate(w, "t2.html", "Golang")
}

func main() {
  server := http.Server{
    Addr: "127.0.0.1:8080",
  }
  
  http.HandleFunc("/t1", handler1)
  http.HandleFunc("/t2", handler2)
  server.ListenAndServe()
}

t1.html

<html>
<head>
  <title>T1 template</title>
</head>
<body>
  Hi, My name is {{ . }}.
</body>
</html>

t2.html

<html>
<head>
  <title>T2 template</title>
</head>
<body>
  Hi, I am learning {{ . }}.
</body>
</html>
本文网址: https://golangnote.com/topic/182.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles