简体   繁体   English

如何仅将变量(不是结构成员)传递到 text/html 模板。 高朗

[英]How to pass just a variable (not a struct member) into text/html template. Golang

is there any way to pass just a variable (string, int, bool) into template.有什么方法可以将变量(字符串、整数、布尔)传递给模板。 For example (something similar):例如(类似的东西):

import (
    "html/template"
)

func main() {
    ....
    tmpl := template.Must(template.ParseFiles("templates/index.html"))
    mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
        varmap := map[string]interface{}{
            "var1": "value",
            "var2": 100,
        }
        tmpl.ExecuteTemplate(rw, "index", varmap)
    })

    // content of index.html
    {{define "index"}}
    {{var1}} is equal to {{var2}}
    {{end}}
}

Yes just use the dot in front of it:是的,只需使用它前面的点:

http://play.golang.org/p/7NXu9SDiik http://play.golang.org/p/7NXu9SDiik

package main

import (
    "html/template"
    "log"
    "os"
)

var tmplString = `    // content of index.html
    {{define "index"}}
    {{.var1}} is equal to {{.var2}}
    {{end}}
`

func main() {
    tmpl, err := template.New("test").Parse(tmplString)
    if err != nil {
        log.Fatal(err)
    }
    varmap := map[string]interface{}{
        "var1": "value",
        "var2": 100,
    }
    tmpl.ExecuteTemplate(os.Stdout, "index", varmap)

}

It is possible to pass just a simple value of any type.可以只传递任何类型的简单值。 If you do so, you can refer to it in the template as {{.}} .如果这样做,您可以在模板中将其称为{{.}}

Here is an example (try it on the Go Playgound ):这是一个示例(在Go Playgound上尝试):

s := "<html><body>Value passed: {{.}}</body></html>\n"

tmpl := template.Must(template.New("test").Parse(s))

tmpl.Execute(os.Stdout, false)
tmpl.Execute(os.Stdout, 1)
tmpl.Execute(os.Stdout, "me")

Output:输出:

<html><body>Value passed: false</body></html>
<html><body>Value passed: 1</body></html>
<html><body>Value passed: me</body></html>

Try fasttemplate [1].尝试快速模板 [1]。 It accepts a map of placeholders' substitution values.它接受占位符替换值的映射。 And it works faster than html/template on simple templates.它在简单模板上的运行速度比 html/template 快。

[1] http://github.com/valyala/fasttemplate [1] http://github.com/valyala/fasttemplate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM