使用golang的標準庫搭建網站--2.模板解析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

模板的解析

既然是搭建網站,

fmt.Fprintf(w, "Hello world, this is my first page!")

這種方式肯定就不能用了,得解析模板才行。
模板解析用到的包是”html/template”,先導包,然後改寫Index函數:

//先匯入html/template包import "html/template"func Index(w http.ResponseWriter, r *http.Request) {    //解析指定模板檔案index.html    t, _ := template.ParseFiles("index.html")    //輸出到瀏覽器    t.Execute(w, nil)}

在準備一個html檔案,如下:

<HTML>    <head>        <title>            這是一個測試檔案        </title>    </head>    <body>        <p>            Hello world, this is my first page!        </p>    </body></HTML>

運行一下,得到和上面一樣的結果。

接著向模板中插入資料,很容易:

func Index(w http.ResponseWriter, r *http.Request) {    //用於儲存資料的map    data := make(map[string]string)    t, _ := template.ParseFiles("index.html")    data["Name"] = "BCL"    t.Execute(w, data)}

在HTML檔案中插入一個新的標籤:

<p> Hello , {{.Name}} </p>

這樣就能正常解析模板啦

下面我們就簡單的瞭解一下go語言的模板的文法

未完待續…….

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.