2017-05-08 78 views
1

我是Golang的新手。如何將值傳遞給靜態頁面?將價值傳遞給靜態頁Golang

假設我有這樣的代碼:

// webtes project main.go 
package main 

import (
    "log" 
    "net/http" 
) 

func main() { 

    http.HandleFunc("/sayName", func(writer http.ResponseWriter, r *http.Request) { 
     name := "Jon Snow" 
     http.ServeFile(writer, r, "static/sayName.html")/*How do I pass 'name' to this static page and print it?*/ 
    }) 

    log.Fatal(http.ListenAndServe(":8081", nil)) 
} 

靜態/ sayName.html

<!doctype html> 
<html> 
    <head></head> 
    <body>{/*print name here*/}</body> 
</html> 

我想通過 「名」 變量靜態頁面 「sayName.html」,並打印有。我如何實現這一目標? THKS。

回答

1

制定sayName.htmlhtml/template的常用方法,並在每個請求上執行它。

那麼你的處理程序是這樣的:

func templateHandler(w http.ResponseWriter, r *http.Request){ 
    tplTxt,err := ioutil.ReadFile(...) 
    //error handling 
    tpl := template.Must(template.New("").Parse(string(tplTxt))) 
    templateData := map[string]interface{}{"Name":"Jon Snow"} 
    tpl.Execute(w, templateData) 
} 

而且你的HTML模板可以使用{{.Name}}插入名稱。

您應該緩存解析的模板並更好地處理錯誤,但這是一般的想法。

+0

非常感謝!順便說一句。我如何在靜態頁面中執行循環? – Angger

+0

{{range .SomeList}} ... {{.SomeField}} ... {{end}} – captncraig