一、渲染
//1.解析模板
temp := template.Must(template.ParseFiles("html/test1.html"))
//2.数据映射及输出模板
temp.Execute(w,"hello world") //Execute 渲染 ParseFiles参数的第一个文件
指定模板名称,中间的名称为文件名称
temp.ExecuteTemplate(w, "test1.index", "hello world") //指定名称渲染特定页面
二、布局
golang 提供可 {{define}} {{block}} {{template}} 三个actions指令,我们可以借助这三个指令实现模板的嵌套及布局
1.{{define "name"}} 内容 {{end}}
定义一个具有指定名称name的代码块,该名称name,主要被用于 模板渲染,以及block template 指令调用
模板渲染指定define的模块
temp.ExecuteTemplate(w, "define的name值", "hello world")
2.{{block "name" data}} 没有匹配到define时的内容 {{end}}
调用一个define定义的name的代码块,并给define模块中传入数据data
3.{{template "name" data}}
嵌套一个define定义的name的代码块,并给define模块中传入数据data
三、实现一个布局
html/layout/layouts.html布局页面
{{define "layout_default"}}
<!DOCTYPE html>
<html lang="en">
<head>
{{block "header" .}}{{end}}
</head>
<body class="gray-bg" style="display: none">
<div class="container-div">
<div class="row">
{{block "content" .}}{{end}}
</div>
</div>
{{block "js_src" .}}{{end}}
{{block "script" .}}{{end}}
</body>
</html>
{{end}}html/layout/include.html 公共资源,可以定义一些通用的代码块
{{define "header"}}
<title>B5GoCMF</title>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link href="/static/admin/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
{{end}}{{define "js_src"}}
<script type="text/javascript" src="/static/admin/plugins/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="/static/admin/plugins/bootstrap/js/bootstrap.min.js"></script>
{{end}}
测试页面html/test/index.html
{{define "test/index"}}
{{template "layout_default" .}}
{{end}}
{{define "content"}}
<div class="col-sm-12 search-collapse">
//页面代码
</div>
{{end}}
{{define "script"}}
<script>
//js代码
</script>
{{end}}渲染布局及调用显示html/test/index.html
func handleTest(w http.ResponseWriter,r *http.Request) {
//1.解析模板 布局文件必须也要解析
layoutFiles :=[]string{"html/layout/layouts.html","html/layout/include.html"}
layoutFiles = append(layoutFiles, "html/test/index.html")
temp := template.Must(template.ParseFiles(layoutFiles...))
//html/test/index.html 页面中定一个了一个自己的test/index
temp.ExecuteTemplate(w, "test/index", "hello world")
}