日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Golang的模板与渲染

發(fā)布時間:2025/3/16 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Golang的模板与渲染 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

模板:提前定義好的html文件
渲染:就是填充數(shù)據(jù)或者說替換字符串
Go語言內(nèi)置了用于HTML文檔的html/template和文本模板引擎text/template。

模板文件通常定義為.tmpl和.tpl為后綴;

必須使用UTF8編碼;

模板文件中使用{{和}}包裹和標(biāo)識需要傳入的數(shù)據(jù),除{{和}}包裹的內(nèi)容外,其他內(nèi)容均不做修改原樣輸出。

hello.tmpl

<!DOCTYPE html> <html lang="zh-CN"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Hello</title> </head> <body> <p>Hello {{.}}</p> </body> </html>

其中,其中{{.}}中的點(diǎn)表示當(dāng)前對象

main.go

package mainimport ("fmt""html/template""net/http" )func sayHello(w http.ResponseWriter, r *http.Request) {// 解析指定文件生成模板對象tmpl, err := template.ParseFiles("./hello.tmpl")if err != nil {fmt.Println("create template failed, err:", err)return}// 利用給定數(shù)據(jù)渲染模板,并將結(jié)果寫入wtmpl.Execute(w, "hello你好") } func main() {http.HandleFunc("/", sayHello)err := http.ListenAndServe(":9090", nil)if err != nil {fmt.Println("HTTP server failed,err:", err)return} }

總結(jié)

以上是生活随笔為你收集整理的Golang的模板与渲染的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。