功能:通过模板使用Go中自定义函数(将邮箱字段的@符号替换为at);
遇见问题:在控制台打印模板输出时字符可以正常替换,但通过浏览器访问渲染模板时无法找到该自定义函数;
模板使用自定义函数步骤:
- 通过 template.New(`PathToHtml`) 分配一个Html模板;
- 调用 template.Funcs(template.FuncMap{"参数名":函数名}) 将实参map的元素添加到模板的函数map中。注意:必须在解析模板之前调用它;
- 解析模板:template.ParseFiles(`PathToHtml`) 注意:template.New() 函数中参数名字要和 template.ParseFiles() 函数的文件名要相同,要不然就会报错:"" is an incomplete template;
- 最后通过 template.ExecuteTemplate(wr io.Writer, name string, data interface{}) error 使用名为name的t关联的模板产生输出;
main.go
package main
type Friend struct {
Fname string
}
type Person struct {
UserName string
Emails []string // 未导出的字段首字母是小写的
Friends []*Friend
}
func EmailDealWith(args ...interface{}) string {
ok := false
var s string
if len(args)