Golang模板中的”minus”函数

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

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 (
	&quot;html/template&quot;
	&quot;net/http&quot;
	&quot;strconv&quot;
)

var funcMap = template.FuncMap{
	&quot;minus&quot;: minus,
}

const tmpl = `
&lt;html&gt;&lt;body&gt;
    &lt;div&gt;
        &lt;span&gt;{{minus 1 2}}&lt;/span&gt;
    &lt;/div&gt;
&lt;/body&gt;&lt;/html&gt;`

var tmplGet = template.Must(template.New(&quot;&quot;).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(&quot;/&quot;, getPageHandler)
	http.ListenAndServe(&quot;:8080&quot;, nil)
}

huangapple
  • 本文由 发表于 2014年7月19日 15:28:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24837883.html
匿名

发表评论

匿名网友

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

确定