英文:
Passing value to static page Golang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对Golang还不熟悉。如何将值传递给静态页面?
假设我有以下代码:
// webtes项目的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")/*我如何将'name'传递给这个静态页面并打印出来?*/
})
log.Fatal(http.ListenAndServe(":8081", nil))
}
static/sayName.html
<!doctype html>
<html>
<head></head>
<body>{/*在这里打印name*/}</body>
</html>
我想将变量"name"传递给静态页面"sayName.html"并在那里打印出来。我该如何实现?谢谢。
英文:
I'm new to Golang. how to I pass value to static page?
suppose I have this code :
// 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))
}
static/sayName.html
<!doctype html>
<html>
<head></head>
<body>{/*print name here*/}</body>
</html>
I want to pass "name" variable to the static page "sayName.html" and print that there. How do I achieve this? thks.
答案1
得分: 2
常见的方法是将sayName.html
作为html/template
处理,并在每个请求上执行它。
然后,你的处理程序可以是这样的:
func templateHandler(w http.ResponseWriter, r *http.Request){
tplTxt,err := ioutil.ReadFile(...)
// 错误处理
tpl := template.Must(template.New("").Parse(string(tplTxt)))
templateData := map[string]interface{}{"Name":"Jon Snow"}
tpl.Execute(w, templateData)
}
你的HTML模板可以使用{{.Name}}
来插入名称。
你应该缓存解析后的模板并更好地处理错误,但这是一般的思路。
英文:
A common approach it to make sayName.html
an html/template
, and execute it on each request.
Then your handler is something like:
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)
}
And your html template can use {{.Name}}
to insert the name.
You should cache the parsed templates and handle errors better, but thats the general idea.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论