Golang html/template模板渲染解析

创建模板文件

1、创建layouts文件夹
2、在layouts文件夹中创建以下三个模板文件
header.html
sidebar.html
footer.html
3、创建template_admin.html模板文件
4、使用{{define "template_name"}}定义模板
5、使用{{template "template_name" .}}引入模板文件,注意标签后面的点"."一定要带上,在引入的模板中解析变量
6、变量输出{{.name}}
目录结构
--|project
    --|layouts
        --|header.html
        --|sidebar.html
        --|footer.html
    --|template_admin.html
    --|content.html
    --|content-1.html
    --|main.go

header.html模板文件中添加

{{define "layouts/header"}}
<header>
    header
header>
{{end}}

sidebar.html模板文件中添加

{{define "layouts/sidebar"}}
<nav>
    sidebar
nav>
{{end}}

footer.html模板文件中添加

{{define "layouts/footer"}}
<footer>
    footer
footer>
{{end}}

template_admin.html模板文件中添加


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.title}}title>
head>
<body>
    
    {{template "layouts/header" .}}
    
    {{template "layouts/sidebar" .}}
    
    {{template "content" .}}
    
    {{template "layouts/footer" .}}
body>
html>

创建content.html与content-1.html模板文件,模板中添加

{{define "content"}}
    <div>
        {{.content}}
    div>
{{end}}

创建main.go文件,main.go文件与layouts目录同级。添加下面代码

type Content map[string]interface{}

func main() {
	LayoutTpl()
}

func LayoutTpl() {
	http.HandleFunc("/content", func(w http.ResponseWriter, r *http.Request) {
		t, err := setAdminContentFile("content.html")
		if err != nil {
			fmt.Println("parse file err:", err.Error())
			return
		}
		p := Content{"title": "admin", "content": "layouts - template - content"}
		_ = t.Execute(w, p)
	})
	http.HandleFunc("/content-1", func(w http.ResponseWriter, r *http.Request) {
		t, err := setAdminContentFile("content-1.html")
		if err != nil {
			fmt.Println("parse file err:", err.Error())
			return
		}
		p := Content{"title": "admin", "content": "layouts - template - content-1"}
		_ = t.Execute(w, p)
	})
	_ = http.ListenAndServe("127.0.0.1:9080", nil)
}

func setAdminContentFile(contentFileName string) (*template.Template, error) {
	files := []string{"template_admin.html", "layouts/header.html",
		"layouts/sidebar.html", contentFileName, "layouts/footer.html"}
	return template.ParseFiles(files...)
}

终端执行:go run main.go
浏览器访问: http://127.0.0.1:9080/content 如下
Golang html/template模板渲染解析_第1张图片
浏览器访问: http://127.0.0.1:9080/content-1 如下
Golang html/template模板渲染解析_第2张图片

你可能感兴趣的:(Golang,go,golang,html)