加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

使用golang的标准库搭建网站--3.模板函数

发布时间:2020-12-16 18:36:12 所属栏目:大数据 来源:网络整理
导读:和大多数语言的的模板语法类似:{{.Name | FuncName}} go本身自带了一些模板函数,我们现在来看一看如何自定义模板函数: 先来看一个函数声明: func (t * Template ) F uncs (func Map FuncMap ) *T emplate Funcs函数就是用来创建我们模板函数的函数了,它

和大多数语言的的模板语法类似:{{.Name | FuncName}}
go本身自带了一些模板函数,我们现在来看一看如何自定义模板函数:
先来看一个函数声明:

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs函数就是用来创建我们模板函数的函数了,它需要一个FuncMap类型的参数,继续看手册

type FuncMap map[string]interface{}

官方文档里是这么解释的

FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value,or two return values of which the second has type error. In that case,if the second (error) argument evaluates to non-nil during execution,execution terminates and Execute returns that error.

简单翻译一下就是
这是一个map,是名称与函数的映射,其中key对应的就是你在模板中使用的函数名称,不一定要和你在源代码文件
中定义的函数名同名,需要注意的是这个map的value,它是一个interface{}类型的,但实际上应该给它一个
指定类型的函数名,这个函数是这样的:

func functionName(args ...interface{}) string

你也可以有第二个返回值,但必须是error类型的。如果函数执行没有出错,那这个值必须是nil,
我们来看一下具体的使用方法:

func Index(w http.ResponseWriter,r *http.Request) {
    //用于保存数据的map
    data := make(map[string]string)
    //保存模板函数
    tempfunc := make(template.FuncMap)
    tempfunc["ShowName"] = ShowName
    t,_ := template.ParseFiles("index.html")
    //注册模板函数
    t = t.Funcs(tempfunc)
    data["Name"] = "BCL"
    t.Execute(w,data)
}
//这个示例函数,将传进来的字符串用*****包起来
func ShowName(args ...interface{}) string {
    //这里只考虑一个参数的情况
    var str string = ""
    if s,ok := args[0].(string); ok {
    str = "*****" + s + "*****"
    } else {
        str = "Nothing"
    }
    return str
}

如果这么写的话,似乎看上去并没有什么问题,并且编译能通过,
打开浏览器访问,发现似乎除了问题:
[4]
并且出现了以下的错误:

2015/07/22 22:38:07 http: panic serving 127.0.0.1:37346: runtime error: invalid memory address or nil pointer dereference
goroutine 5 [running]:
net/http.func·011()
/opt/go/src/net/http/server.go:1130 +0xbb
html/template.(*Template).Funcs(0x0,0xc20803af30,0x1)
/opt/go/src/html/template/template.go:276 +0x1f
main.Index(0x7fda0d28a278,0xc20804cc80,0xc208032d00)
/home/buchenglei/workspace/golang/src/test/test.go:18 +0x121
net/http.HandlerFunc.ServeHTTP(0x7cee28,0x7fda0d28a278,0xc208032d00)
/opt/go/src/net/http/server.go:1265 +0x41
net/http.(*ServeMux).ServeHTTP(0xc20803aa20,0xc208032d00)
/opt/go/src/net/http/server.go:1541 +0x17d
net/http.serverHandler.ServeHTTP(0xc208070060,0xc208032d00)
/opt/go/src/net/http/server.go:1703 +0x19a
net/http.(*conn).serve(0xc20804cbe0)
/opt/go/src/net/http/server.go:1204 +0xb57
created by net/http.(*Server).Serve
/opt/go/src/net/http/server.go:1751 +0x35e

需要改写模板解析的函数

func Index(w http.ResponseWriter,r *http.Request) {
    //用于保存数据的map
    data := make(map[string]string)
    tempfunc := make(template.FuncMap)
    tempfunc["showname"] = ShowName
    //得给模板起个名字才行
    t := template.New("index.html")
    t = t.Funcs(tempfunc)
    t,_ = t.ParseFiles("./index.html")
    data["Name"] = "BCL"
    t.Execute(w,data)
}

这样即可得到正确的输出结果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读