Use template engine, hope it will be helpful to friends in need!
1 OverviewWhen processing the response body, the most common way is to send the processed HTML code. Since the data needs to be Embedded into HTML, then a template engine is the best choice.In the Go language, the
html/template
main.go
package mainimport ( "html/template" "log" "net/http")func main() { // 设置 处理函数 http.HandleFunc("/", TestAction) 开启监听(监听浏览器请求) log.Fatal(http.ListenAndServe(":8084", nil))}func TestAction(w http.ResponseWriter, r *http.Request) { // 解析模板 t, _ := template.ParseFiles("template/index.html") // 设置模板数据 data := map[string]interface{}{ "User": "小韩说课", "List": []string{"Go", "Python", "PHP", "JavaScript"}, } // 渲染模板,发送响应 t.Execute(w, data)}
template/index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>小韩说课</title></head><body>Hello, {{ .User }}<br>你熟悉的技术:<ul>{{ range .List }} <li>{{.}}</li>{{end}}</ul></body></html>
The above code completes the basic use of the template engine, including parsing templates, rendering data, and responding to result operations. Details follow.
The above is the detailed content of How to use template engine in Go language. For more information, please follow other related articles on the PHP Chinese website!