久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      Go語言中如何使用模板引擎

      下面由golang教程欄目給大家介紹Go語言中使用模板引擎,希望對需要的朋友有所幫助!

      Go語言中如何使用模板引擎

      1 概述

      處理響應主體時,最常見的方式就是發(fā)送處理好的 HTML 代碼,由于需要將數(shù)據(jù)嵌入到 HTML 中,那么模板引擎(template engine)就是最好的選擇。

      Go語言中,提供了 html/template 包,實現(xiàn)模板引擎的相關功能??焖偈褂檬纠?/p>

      main.go

      package mainimport (   "html/template"   "log"   "net/http")func main() {   // 設置 處理函數(shù)   http.HandleFunc("/", TestAction)    開啟監(jiān)聽(監(jiān)聽瀏覽器請求)   log.Fatal(http.ListenAndServe(":8084", nil))}func TestAction(w http.ResponseWriter, r *http.Request) {   // 解析模板   t, _ := template.ParseFiles("template/index.html")   // 設置模板數(shù)據(jù)   data := map[string]interface{}{     "User": "小韓說課",     "List": []string{"Go", "Python", "PHP", "JavaScript"},   }   // 渲染模板,發(fā)送響應   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>

      執(zhí)行結果:

      Go語言中如何使用模板引擎

      以上代碼就完了模板引擎的基本使用,包括解析模板,渲染數(shù)據(jù),響應結果操作。接下來詳細說明。

      2 解析模板

      函數(shù) template.ParseFiles(filenames ...string) (*Template, error) 可以解析模板文件,并得到模板對象。參數(shù)為模板文件。同時會以模板文件的文件名(不包含后綴名)作為模板的名字。

      還可以使用 template.New("name").Parse(src string) 來創(chuàng)建模板對象,并完成解析模板內容。

      3 應用數(shù)據(jù)并發(fā)送響應

      函數(shù) func (t *Template) Execute(wr io.Writer, data interface{}) error 將 data 應用到解析好的模板上,并將輸出寫入 wr。如果執(zhí)行時出現(xiàn)錯誤,會停止執(zhí)行,但有可能已經寫入wr部分數(shù)據(jù)。

      data 數(shù)據(jù)可以接受任意類型,最常見的類型為:map[string]interface{},通過不同的下標來區(qū)分部分的分配數(shù)據(jù)。在模板中使用 .User,.List 來訪問分配數(shù)據(jù)中的 User 和 List。

      完!

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號