【问题标题】:Golang templates "minus" functionGolang 模板“减号”功能
【发布时间】:2014-09-10 08:26:51
【问题描述】:

我知道在go 模板中,我可以调用名为add 的函数来表达1 + 1 之类的表达式。但是像2 - 1这样的表达式如何命名函数?

【问题讨论】:

    标签: function templates go


    【解决方案1】:

    默认不包含add 函数。但是,您可以自己轻松编写此类函数。例如:

    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】:

      你总是可以定义这样的函数:

      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)
      }
      

      【讨论】:

      • 有使用int64strconv的理由吗?另一个答案stackoverflow.com/a/24838014/10245 没有,并且为我避免了 int/int64 转换错误。谢谢你的回答,它很有用。
      • @TimAbell 4 年后,我不记得了。 golang.org/pkg/strconv/#FormatInt 有错误吗?
      • 大声笑,我显然迟到了。错误是将模板中的文字 int 转换为 int64。我没有进一步研究。
      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 2010-09-13
      • 2014-05-03
      相关资源
      最近更新 更多