![](/img/trans.png)
[英]Golang. html/template. How to put a unquoted string to <script>?
[英]How to pass just a variable (not a struct member) into text/html template. Golang
有什么方法可以將變量(字符串、整數、布爾)傳遞給模板。 例如(類似的東西):
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}}
}
是的,只需使用它前面的點:
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)
}
可以只傳遞任何類型的簡單值。 如果這樣做,您可以在模板中將其稱為{{.}}
。
這是一個示例(在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")
輸出:
<html><body>Value passed: false</body></html>
<html><body>Value passed: 1</body></html>
<html><body>Value passed: me</body></html>
嘗試快速模板 [1]。 它接受占位符替換值的映射。 它在簡單模板上的運行速度比 html/template 快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.