在伺服器端渲染頁面到瀏覽器端,這部分也是前後端模糊的地帶,
因為有樣版引擎的存在,讓義大利式的開發很有機會發生,
在使用類似的樣版引擎的時候,要特別小心,盡量不讓過多的邏輯出現在樣板當中。
在 Golang 中使用樣板
package main
import (
	"fmt"
	"html/template"
	"net/http"
)
func helloworld(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("helloworld.html")
	t.Execute(w, "Hello World!")
}
func main() {
	addr := "127.0.0.1:8080"
	server := http.Server{
		Addr: addr,
	}
	http.HandleFunc("/", helloworld)
	fmt.Printf("server on " + addr)
	server.ListenAndServe()
}
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>{{ . }}</title>
</head>
<body>
    {{ . }}
</body>
</html>
使用 template.ParseFiles 解析樣板檔案,
其中傳回的物件中的方法 Execute,來嵌入變數,
達成渲染樣板