zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Go语言之自定义模板,引用多个模板html文件嵌套使用

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

在这里插入图片描述