How to send variable and its value to html

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

How to send variable and its value to html

问题

我已经用Go语言写了一小段代码。

func loginHandler(w http.ResponseWriter, r *http.Request) {
    log.Println("loginHandler")
    log.Println("request url is", r.RequestURI)
    log.Println("request method", r.Method)
    requestbody, _ := ioutil.ReadAll(r.Body)
    log.Println("request body is", string(requestbody))
    if r.Method == "POST" {
        us, err := globalSessions.SessionStart(w, r)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        us.Set("LoggedInUserID", "000000")
        w.Header().Set("Location", "/auth")
        w.WriteHeader(http.StatusFound)
        return
    }
    outputHTML(w, r, "static/login.html")
}

func outputHTML(w http.ResponseWriter, req *http.Request, filename string) {
    log.Println("outputHTML")
    requestbody, _ := ioutil.ReadAll(req.Body)
    log.Println("request body is", string(requestbody))
    log.Println("request body is", requestbody)
    file, err := os.Open(filename)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    defer file.Close()
    fi, _ := file.Stat()
    http.ServeContent(w, req, file.Name(), fi.ModTime(), file)
}

在这段代码中,我将重定向到login.html。现在我想要发送一个变量,假设它是一个名为testvariable的字符串,并将其值传递给login.html

英文:

I have written a small piece of code in go

func loginHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("loginHandler")
	log.Println("request url is", r.RequestURI)
	log.Println("request method", r.Method)
	requestbody, _ := ioutil.ReadAll(r.Body)
	log.Println("request body is", string(requestbody))
	if r.Method == "POST" {
		us, err := globalSessions.SessionStart(w, r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		us.Set("LoggedInUserID", "000000")
		w.Header().Set("Location", "/auth")
		w.WriteHeader(http.StatusFound)
		return
	}
	outputHTML(w, r, "static/login.html")
}

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

func outputHTML(w http.ResponseWriter, req *http.Request, filename string) {
	log.Println(&quot;outputHTML&quot;)
	requestbody, _ := ioutil.ReadAll(req.Body)
	log.Println(&quot;request body is&quot;, string(requestbody))
	log.Println(&quot;request body is&quot;, requestbody)
	file, err := os.Open(filename)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	defer file.Close()
	fi, _ := file.Stat()
	http.ServeContent(w, req, file.Name(), fi.ModTime(), file)
}

<!-- end snippet -->

in this code i am redirecting to login.html . now i want to send a variable let it be some string called testvariable and its value to login.html.

答案1

得分: 3

要在你的HTML中显示值,你可以使用Go的html/template包。

首先,你需要指定在HTML页面中希望出现值的位置,使用html/template包,你可以通过模板操作来实现。

"操作" - 数据评估或控制结构 - 由"{{"和"}}"界定

接下来,你需要放弃http.ServeContent函数,因为它不知道如何渲染模板,而是可以使用Execute来显示登录页面以及你的值。

这是一个示例:

login.html:

<html>
    <body>
        <h1>{{.MyVar}}</h1>
    </body>
</html>

outputHTML:

func outputHTML(w http.ResponseWriter, filename string, data interface{}) {
	t, err := template.ParseFiles(filename)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	if err := t.Execute(w, data); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
}

以及你的loginHandler:

func loginHandler(w http.ResponseWriter, r *http.Request) {

    // 做你需要做的事情
    
    myvar := map[string]interface{}{"MyVar": "Foo Bar Baz"}
    outputHTML(w, "static/login.html", myvar)
}

在这里阅读更多关于模板的信息:html/template,有关如何编写模板本身的信息,请参阅text/template的文档。

英文:

To be able to display values in your html you can use Go's html/template package.

First you'll need to specify where in the html page you want your values to appear, using the html/template package you can do that with template actions.

> "Actions"--data evaluations or control structures--are delimited by
> "{{" and "}}"

Next you'll need to drop the http.ServeContent function as that does not know how to render templates, instead you can use Execute to display the login page together with your values.

Here's an example:

login.html:

&lt;html&gt;
    &lt;body&gt;
        &lt;h1&gt;{{.MyVar}}&lt;/h1&gt;
    &lt;/body&gt;
&lt;/html&gt;

outputHTML:

func outputHTML(w http.ResponseWriter, filename string, data interface{}) {
	t, err := template.ParseFiles(filename)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	if err := t.Execute(w, data); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
}

And your loginHandler:

func loginHandler(w http.ResponseWriter, r *http.Request) {

    // do whatever you need to do
    
    myvar := map[string]interface{}{&quot;MyVar&quot;: &quot;Foo Bar Baz&quot;}
    outputHTML(w, &quot;static/login.html&quot;, myvar)
}

Read more on templates here: html/template and for information about how to program the templates themselves, see the documentation for text/template

huangapple
  • 本文由 发表于 2017年4月18日 21:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/43473046.html
匿名

发表评论

匿名网友

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

确定