将值传递给静态页面 Golang

huangapple go评论91阅读模式
英文:

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 (
	&quot;log&quot;
	&quot;net/http&quot;
)

func main() {

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

	log.Fatal(http.ListenAndServe(&quot;:8081&quot;, nil))
}

static/sayName.html

&lt;!doctype html&gt;
&lt;html&gt;
   &lt;head&gt;&lt;/head&gt;
   &lt;body&gt;{/*print name here*/}&lt;/body&gt;
&lt;/html&gt;

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(&quot;&quot;).Parse(string(tplTxt)))
   templateData := map[string]interface{}{&quot;Name&quot;:&quot;Jon Snow&quot;}
   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.

huangapple
  • 本文由 发表于 2017年5月9日 01:07:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/43853442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定