英文:
Golang templates "minus" function
问题
我知道在go
模板中,我可以使用名为add
的函数来计算表达式1 + 1
。但是对于表达式2 - 1
,应该使用什么函数名称呢?
英文:
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
?
答案1
得分: 13
默认情况下,没有包含add
函数。但是,你可以很容易地自己编写这样的函数。例如:
tmpl := template.Must(template.New("").Funcs(template.FuncMap{
"add": func(a, b int) int {
return a + b
},
}).Parse("{{ add 5 2 }}"))
tmpl.Execute(os.Stdout, nil)
英文:
There is no add
function included by default. You can however, easily write such functions yourself. For example:
tmpl := template.Must(template.New("").Funcs(template.FuncMap{
"minus": func(a, b int) int {
return a - b
},
}).Parse("{{ minus 5 2 }}"))
tmpl.Execute(os.Stdout, nil)
答案2
得分: 7
你可以始终定义这样一个函数:
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论