1 Star 0 Fork 3

源码大数据(codebigdata) / goWebActualCombat

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
2.4-template-funcs.go 1.68 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2021-06-08 11:59 . update
//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 仓库地址:https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址:https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
)
func Welcome() string { //无参数函数
return "Welcome"
}
func Doing(name string) string { //有参数函数
return name + ", Learning Go Web template "
}
func sayHello(w http.ResponseWriter, r *http.Request) {
htmlByte, err := ioutil.ReadFile("./funcs.html")
if err != nil {
fmt.Println("read html failed, err:", err)
return
}
// 自定义一个匿名模板函数
loveGo := func() string {
return "欢迎一起学习《Go Web编程实战派——从入门到精通》"
}
// 链式操作在Parse()方法之前调用Funcs()函数,用来添加自定义的loveGo函数
tmpl1, err := template.New("funcs").Funcs(template.FuncMap{"loveGo": loveGo}).Parse(string(htmlByte))
if err != nil {
fmt.Println("create template failed, err:", err)
return
}
funcMap := template.FuncMap{
//在FuncMap中声明要使用的函数,然后就能够在模板的字符串中使用该函数
"Welcome": Welcome,
"Doing": Doing,
}
name := "Shirdon"
tmpl2, err := template.New("test").Funcs(funcMap).
Parse("{{Welcome}}\n{{Doing .}}\n")
if err != nil {
panic(err)
}
// 使用user渲染模板,并将结果写入w
tmpl1.Execute(w, name)
tmpl2.Execute(w, name)
}
func main() {
http.HandleFunc("/", sayHello)
http.ListenAndServe(":8087", nil)
}
Go
1
https://gitee.com/codebigdata/goWebActualCombat.git
git@gitee.com:codebigdata/goWebActualCombat.git
codebigdata
goWebActualCombat
goWebActualCombat
b84124f40e18

搜索帮助