Golang模板“minus”功能 [英] Golang templates "minus" function
问题描述
我知道在去模板中,我可以为
等表达式调用名为
。但是,如何为表达式命名函数如的函数add
1 + 1 2 - 1
?
您总是可以定义这样一个函数:
pre $ $ $ $ $ $ $ $
$ import
html /模板
net / http
strconv
)
var funcMap = template.FuncMap {
minus:minus,
}
const tmpl =`
< html>< body>
< div>
< span> {{减1 2}}< / span>
< / div>
< / body>< / html>`
var tmplGet = template.Must(template.New()。Funcs(funcMap).Parse(tmpl))
func减(a,b int64)string {
返回strconv.FormatInt(ab,10)
}
func getPageHandler(w http.ResponseWriter, r * http.Request){
if err:= tmplGet.Execute(w,nil); err!= nil {
http.Error(w,err.Error(),http.StatusInternalServerError)
}
}
func main(){
http.HandleFunc(/,getPageHandler)
http.ListenAndServe(:8080,nil)
}
I know that in go
templates I can call function named add
for expression like 1 + 1
. But how named function for expression like 2 - 1
?
You could always define such a function:
package main
import (
"html/template"
"net/http"
"strconv"
)
var funcMap = template.FuncMap{
"minus": minus,
}
const tmpl = `
<html><body>
<div>
<span>{{minus 1 2}}</span>
</div>
</body></html>`
var tmplGet = template.Must(template.New("").Funcs(funcMap).Parse(tmpl))
func minus(a, b int64) string {
return strconv.FormatInt(a-b, 10)
}
func getPageHandler(w http.ResponseWriter, r *http.Request) {
if err := tmplGet.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", getPageHandler)
http.ListenAndServe(":8080", nil)
}
这篇关于Golang模板“minus”功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!