Go html/template 模板的使用实例详解
作者:big_cat 发布时间:2024-04-26 17:17:00
从字符串载入模板
我们可以定义模板字符串,然后载入并解析渲染:
template.New(tplName string).Parse(tpl string)
// 从字符串模板构建
tplStr := `
{{ .Name }} {{ .Age }}
`
// if parse failed Must will render a panic error
tpl := template.Must(template.New("tplName").Parse(tplStr))
tpl.Execute(os.Stdout, map[string]interface{}{Name: "big_cat", Age: 29})
从文件载入模板
模板语法
模板文件,建议为每个模板文件显式的定义模板名称: {{ define "tplName" }} ,否则会因模板对象名与模板名不一致,无法解析(条件分支很多,不如按一种标准写法实现),另展示一些基本的模板语法。
使用 {{ define "tplName" }} 定义模板名
使用 {{ template "tplName" . }} 引入其他模板
使用 . 访问当前数据域:比如 range 里使用 . 访问的其实是循环项的数据域
使用 $. 访问绝对顶层数据域
views/header.html
{{ define "header" }}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{ .PageTitle }}</title>
</head>
{{ end }}
views/footer.html
{{ define "footer" }}
</html>
{{ end }}
views/index/index.html
{{ define "index/index" }}
{{/*引用其他模板 注意后面的 . */}}
{{ template "header" . }}
<body>
<div>
hello, {{ .Name }}, age {{ .Age }}
</div>
</body>
{{ template "footer" . }}
{{ end }}
views/news/index.html
{{ define "news/index" }}
{{ template "header" . }}
<body>
{{/* 页面变量定义 */}}
{{ $pageTitle := "news title" }}
{{ $pageTitleLen := len $pageTitle }}
{{/* 长度 > 4 才输出 eq ne gt lt ge le */}}
{{ if gt $pageTitleLen 4 }}
<h4>{{ $pageTitle }}</h4>
{{ end }}
{{ $c1 := gt 4 3}}
{{ $c2 := lt 2 3 }}
{{/*and or not 条件必须为标量值 不能是逻辑表达式 如果需要逻辑表达式请先求值*/}}
{{ if and $c1 $c2 }}
<h4>1 == 1 3 > 2 4 < 5</h4>
{{ end }}
<div>
<ul>
{{ range .List }}
{{ $title := .Title }}
{{/* .Title 上下文变量调用 func param1 param2 方法/函数调用 $.根节点变量调用 */}}
<li>{{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}</li>
{{end}}
</ul>
{{/* !empty Total 才输出*/}}
{{ with .Total }}
<div>总数:{{ . }}</div>
{{ end }}
</div>
</body>
{{ template "footer" . }}
{{ end }}
template.ParseFiles
手动定义需要载入的模板文件,解析后制定需要渲染的模板名 news/index 。
// 从模板文件构建
tpl := template.Must(
template.ParseFiles(
"views/index/index.html",
"views/news/index.html",
"views/header.html",
"views/footer.html",
),
)
// render template with tplName index
_ = tpl.ExecuteTemplate(
os.Stdout,
"index/index",
map[string]interface{}{
PageTitle: "首页",
Name: "big_cat",
Age: 29,
},
)
// render template with tplName index
_ = tpl.ExecuteTemplate(
os.Stdout,
"news/index",
map[string]interface{}{
"PageTitle": "新闻",
"List": []struct {
Title string
CreatedAt time.Time
}{
{Title: "this is golang views/template example", CreatedAt: time.Now()},
{Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
},
"Total": 1,
"Author": "big_cat",
},
)
template.ParseGlob
手动的指定每一个模板文件,在一些场景下难免难以满足需求,我们可以使用通配符正则匹配载入。
1、正则不应包含文件夹,否则会因文件夹被作为视图载入无法解析而报错
2、可以设定多个模式串,如下我们载入了一级目录和二级目录的视图文件
// 从模板文件构建
tpl := template.Must(template.ParseGlob("views/*.html"))
template.Must(tpl.ParseGlob("views/*/*.html"))
// render template with tplName index
// render template with tplName index
_ = tpl.ExecuteTemplate(
os.Stdout,
"index/index",
map[string]interface{}{
PageTitle: "首页",
Name: "big_cat",
Age: 29,
},
)
// render template with tplName index
_ = tpl.ExecuteTemplate(
os.Stdout,
"news/index",
map[string]interface{}{
"PageTitle": "新闻",
"List": []struct {
Title string
CreatedAt time.Time
}{
{Title: "this is golang views/template example", CreatedAt: time.Now()},
{Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
},
"Total": 1,
"Author": "big_cat",
},
)
Web服务器
结合模板库和 Gin 实现一个可以使用模板渲染并返回 html 页面的 web 服务。
package main
import (
"html/template"
"log"
"net/http"
"time"
)
var (
htmlTplEngine *template.Template
htmlTplEngineErr error
)
func init() {
// 初始化模板引擎 并加载各层级的模板文件
// 注意 views/* 不会对子目录递归处理 且会将子目录匹配 作为模板处理造成解析错误
// 若存在与模板文件同级的子目录时 应指定模板文件扩展名来防止目录被作为模板文件处理
// 然后通过 view/*/*.html 来加载 view 下的各子目录中的模板文件
htmlTplEngine = template.New("htmlTplEngine")
// 模板根目录下的模板文件 一些公共文件
_, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*.html")
if nil != htmlTplEngineErr {
log.Panic(htmlTplEngineErr.Error())
}
// 其他子目录下的模板文件
_, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*/*.html")
if nil != htmlTplEngineErr {
log.Panic(htmlTplEngineErr.Error())
}
}
// index
func IndexHandler(w http.ResponseWriter, r *http.Request) {
_ = htmlTplEngine.ExecuteTemplate(
w,
"index/index",
map[string]interface{}{"PageTitle": "首页", "Name": "sqrt_cat", "Age": 25},
)
}
// news
func NewsHandler(w http.ResponseWriter, r *http.Request) {
_ = htmlTplEngine.ExecuteTemplate(
w,
"news/index",
map[string]interface{}{
"PageTitle": "新闻",
"List": []struct {
Title string
CreatedAt time.Time
}{
{Title: "this is golang views/template example", CreatedAt: time.Now()},
{Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
},
"Total": 1,
"Author": "big_cat",
},
)
}
func main() {
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/index", IndexHandler)
http.HandleFunc("/news", NewsHandler)
serverErr := http.ListenAndServe(":8085", nil)
if nil != serverErr {
log.Panic(serverErr.Error())
}
}
注意 :模板对象是有名字属性的, template.New("tplName") ,如果没有显示的定义名字,则会使用第一个被载入的视图文件的 baseName 做默认名,比如我们使用 template.ParseFiles/template.ParseGlob 直接生成模板对象时,没有指定模板对象名,则会使用第一个被载入的文件,比如 views/index/index.html 的 baseName 即 index.html 做默认名,而后如果 tplObj.Execute 方法执行渲染时,会去查找名为 index.html 的模板,所以常用的还是 tplObj.ExecuteTemplate 自己指定要渲染的模板名,省的一团乱。
来源:https://studygolang.com/articles/20713


猜你喜欢
- 当我们采用s=[[0]*3]*2初始化一个数组,然后对s[0][0]进行赋值,改变的是第一列所有的值。因为用s = [[0]*3]*2 初始
- 今天为大家分享一下我自己制作的浏览器滚动条,我们知道用css来自定义滚动条也是挺好的方式,css虽然能够改变chrome浏览器的滚动条样式可
- 每次讲解SQL Server里的锁和阻塞(Locking & Blocking)都会碰到的问题:在SQL Server里,为什么我们
- MySQL是一种开放源代码的关系型数据库管理系统(RDBMS),MySQL数据库系统使用最常用的数据库管理语言--结构化查询语言(SQL)进
- Python中有许多方便的库可以用来进行数据处理,尤其是Numpy和Pandas,再搭配matplot画图专用模块,功能十分强大。CSV(C
- vue卡片翻转轮播展示,同时在翻转时切换数据,供大家参考,具体内容如下效果及代码代码:<template> <
- 进行NodeJs开发时偶然发现的一个雷点正常情况下从JSON文件读取到字符后再通过JSON.parse没什么问题,只要格式不出错有时在确保J
- 在如今的Web设计中,图片的应用是必不可少的,为了更好地设计网站效果,大体积的图片被越来越多地应用到Web设计中来,所以,更好地优化图片文件
- pytorch更新完后合并了Variable与Tensortorch.Tensor()能像Variable一样进行反向传播的更新,返回值为T
- 1 什么是K8ssandraCassandra是一款非常优秀的开源的分布式NoSQL数据库,被许多优秀的大公司采用,具有高可用、弹性扩展、性
- 引言大纲这个月我会整理分享一系列后端工程师求职面试相关的文章,知识脉络图如下:JAVA/GO/PHP 面试常问的知识点DB:MySql Pg
- 一个改进的仿google页面拖拽效果,移植方便。web2.0网站经常会用有这个拖拽页面布局的功能,如果你也想给你的网站加上这个有趣的功能,不
- 使用使用navicat连接远程linux mysql数据库出现10061未知故障,设置使用ssh连接后出现2013故障本机环境:win10
- 用科讯CMS“分页显示(专题)文章列表标签”,可以在栏目文章列表下面产生一个页码行。从图可以看出,这段DIV,还需要CSS修饰,但是查看Ht
- 时间差函数TIMESTAMPDIFF、DATEDIFF的用法我们在写sql语句,尤其是存储过程中,会频繁用到对于日期、时间的比较和判断,那么
- 读文件打开文件(文件需要存在)#打开文件f = open("data.txt","r")  
- 一、类和对象通俗理解:类就是模板,对象就是通过模板创造出来的物体类(Class)由3个部分构成:类的名称: 类名类的属性: 一组数据类的方法
- 最近在网上经常看到朋友们聊到UEO,我就想哈UEO是啥东西啊,我去找啦些资料看,他们都说将来UEO发展一定会比较好,我也说这是肯定的.我为什
- monfs :我想知道javascript是否可以实现这样的功能来改变本地的IP地址,例如我本地设置的IP地址是192.168.0.1,我想
- os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname") 改