Go语言之自定义模板,引用多个模板html文件嵌套使用
2023-09-27 14:25:55 时间
在上一篇博客博客的基础上,改成模板嵌套方式
制作流程:
1、同样是先定义一个处理接口/tmpl
,当访问到http://ip:9090/tmpl
时,会处理ti
函数
2、定义t1
函数,这个函数解析了两个模板1.tmpl 2.tmpl
,这里需要注意的是第一个模板是父模板,其中包含了第二个模板,所以第一个模板必须先写
3、1.tmpl
使用define
函数生成了一个内部模板,而2.tmpl
是与1.tmpl
同一目录级别的文件。这里只是引申一下define知识点
目录结构:
main.go
1.tmpl
2.tmpl
p6.tmpl
main.go内容
package main
import (
"fmt"
"html/template"
"net/http"
)
func f1(w http.ResponseWriter, r *http.Request) {
//嵌套一个函数,要么赋值一个,要么第二个值必须是error
k := func(name string) (string, error) {
return name + "Gin框架", nil
}
//定义模板
//在p6.tmpl编辑
//解析模板
t := template.New("p6.tmpl") //定义一个新的模板名称为p6.tmpl
t.Funcs(template.FuncMap{ //固定函数格式
"kua": k, //自定义“kua”必须与同级目录p6.tmpl文件引用的一致
})
_, err := t.ParseFiles("./p6.tmpl") //使用ctrl得知,这里需要两个返回值,所以赋值两个
if err != nil { //错误处理
fmt.Printf("parse template failed,err%v", err)
return
}
name := "Go语言" //声明值
//渲染模板
t.Execute(w, name) //w代表写入,name对应同级目录p6.tmpl文件中的点.
}
func t1(w http.ResponseWriter, r *http.Request) {
//定义模板
//解析模板
t, err := template.ParseFiles("./1.tmpl", "./2.tmpl")
if err != nil {
fmt.Printf("parse template failed,err%v", err)
return
}
//渲染模板
name := "GO语言嵌套模板使用"
t.Execute(w, name)
}
func main() {
http.HandleFunc("/", f1) //当请求到/根目录时,处理f1函数
http.HandleFunc("/tmpl", t1)
err := http.ListenAndServe(":9000", nil) //监听9000端口号
if err != nil { //错误处理
fmt.Println("HTTP server start failed, err:%v", err)
return
}
}
1.tmpl内容
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>自定义嵌套模板函数</title>
</head>
<body>
{{/*template 引用模板文件*/}}
{{template "2.tmpl"}}
{{/*hr代表中横线*/}}
<hr>
{{template "11.tmpl"}}
<hr>
{{/*.代表go代码中的name会传输进来*/}}
{{ . }}
</body>
</html>
{{/*define自定义内部模板*/}}
{{define "11.tmpl"}}
<ol>
<li>吃饭</li>
<li>睡觉</li>
<li>打豆豆</li>
</ol>
{{end}}
2.tmpl内容
<ul>
<li>吃饭</li>
<li>睡觉</li>
<li>打豆豆</li>
</ul>
p6.tmpl内容
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>自定义模板函数</title>
</head>
<body>
{{ kua . }}
</body>
</html>
运行程序:
go run main.go
浏览器访问:
http://ip:9000/tmpl
相关文章
- Go语言strings包
- 用Go向MySQL导入.csv文件
- chaosblade-exec-os项目的burnio.go文件解读
- Minimizing Go WebAssembly Binary Size
- go语言读写文件
- 0137-Go-文件路径
- 0101-Go-通道方向
- 【一天一门编程语言】用 Go 语言实现一个 DAG 任务调度系统的API 接口代码
- Go语言之Gin框架,引用多个HTML文件,并引用函数,解析html代码
- GO_08:GO语言基础之interface
- 让 Pokémon GO 运行在谷歌云服务上
- go module文件下载后的位置
- 【Go 专家编程】go.mod 文件中的indirect准确含义
- 初学 go 入门-案例-教程-记录(12)webapi 框架 Gin(四)前端请求并接收 Json
- [区块链go]windows系统中安装Go与环境变量配置
- Go语言,互斥锁使用
- Go简单的Goroutine示例