Go html/template 模板的使用实例详解
怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Go html/template 模板的使用实例详解》,涉及到html模板、template模板,有需要的可以收藏一下
从字符串载入模板
我们可以定义模板字符串,然后载入并解析渲染:
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" }}
{{ .PageTitle }}
{{ end }}
views/footer.html
{{ define "footer" }}
{{ end }}
views/index/index.html
{{ define "index/index" }}
{{/*引用其他模板 注意后面的 . */}}
{{ template "header" . }}
hello, {{ .Name }}, age {{ .Age }}
{{ template "footer" . }}
{{ end }}
views/news/index.html
{{ define "news/index" }}
{{ template "header" . }}
{{/* 页面变量定义 */}}
{{ $pageTitle := "news title" }}
{{ $pageTitleLen := len $pageTitle }}
{{/* 长度 > 4 才输出 eq ne gt lt ge le */}}
{{ if gt $pageTitleLen 4 }}
{{ $pageTitle }}
{{ end }}
{{ $c1 := gt 4 3}}
{{ $c2 := lt 2 3 }}
{{/*and or not 条件必须为标量值 不能是逻辑表达式 如果需要逻辑表达式请先求值*/}}
{{ if and $c1 $c2 }}
1 == 1 3 > 2 4
{{ end }}
{{ range .List }}
{{ $title := .Title }}
{{/* .Title 上下文变量调用 func param1 param2 方法/函数调用 $.根节点变量调用 */}}
- {{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}
{{end}}
{{/* !empty Total 才输出*/}}
{{ with .Total }}
总数:{{ . }}
{{ end }}
{{ 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 自己指定要渲染的模板名,省的一团乱。
以上就是《Go html/template 模板的使用实例详解》的详细内容,更多关于golang的资料请关注golang学习网公众号!
对Golang import 导入包语法详解
- 上一篇
- 对Golang import 导入包语法详解
- 下一篇
- go流程控制代码详解
-
- 感动的发夹
- 这篇技术贴出现的刚刚好,太全面了,受益颇多,码住,关注up主了!希望up主能多写Golang相关的文章。
- 2022-12-30 12:46:26
-
- 害羞的夕阳
- 真优秀,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢作者大大分享文章内容!
- 2022-12-28 07:53:39
-
- Golang · Go教程 | 17分钟前 |
- Go FlagSet 怎样让子命令独立解析
- 110浏览 收藏
-
- Golang · Go教程 | 18分钟前 |
- Go list 怎样维护 LRU 访问顺序
- 401浏览 收藏
-
- Golang · Go教程 | 20分钟前 |
- Go heap 怎样实现优先级任务队列
- 146浏览 收藏
-
- Golang · Go教程 | 25分钟前 | Go rune unicode strings.IndexFunc 字符串定位
- Go strings.IndexFunc 怎样按字符规则定位位置
- 393浏览 收藏
-
- Golang · Go教程 | 29分钟前 | Go crypto/rand RawURLEncoding Base64url URL令牌
- Go 怎样生成无填充 URL 令牌
- 480浏览 收藏
-
- Golang · Go教程 | 29分钟前 | 并发 · 缓存 · 性能优化 · 正则表达式 · Go教程 · 正则表达式 Go 并发缓存 MustCompile regexp.Compile Regexp缓存
- Go 怎样缓存正则编译结果
- 349浏览 收藏
-
- Golang · Go教程 | 32分钟前 | 文件处理 · 标准库 · Go教程 · io.Copy Go流式读取 Go文件摘要 Go SHA-256 sha256.New
- Go 怎样边读文件边计算摘要
- 133浏览 收藏
-
- Golang · Go教程 | 32分钟前 | Go 单元测试 crypto/rand 依赖注入 io.Reader
- Go crypto/rand 随机源的测试替换方案与生产边界
- 453浏览 收藏
-
- Golang · Go教程 | 35分钟前 |
- Go TLS 怎样处理证书主机名匹配
- 235浏览 收藏
-
- Golang · Go教程 | 38分钟前 | 标准库 · go · https · tls Go crypto/tls crypto/x509 RootCAs 自定义证书
- Go TLS 怎样让客户端信任自定义证书
- 307浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 582次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 620次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 652次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 617次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 434次使用
-
- Go html/template.Clone 怎么派生不同页面模板
- 2026-10-04 361浏览

