Golang模板“minus”功能 [英] Golang templates "minus" function

查看:125
本文介绍了Golang模板“minus”功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在去模板中,我可以为等表达式调用名为的函数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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆