侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Go html/template 模板的使用实例详解

Go  /  管理员 发布于 5年前   374

从字符串载入模板

我们可以定义模板字符串,然后载入并解析渲染:

template.New(tplName string).Parse(tpl string)

// 从字符串模板构建tplStr := `  {{ .Name }} {{ .Age }}`// if parse failed Must will render a panic errortpl := 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 mainimport (  "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())  }}// indexfunc IndexHandler(w http.ResponseWriter, r *http.Request) {  _ = htmlTplEngine.ExecuteTemplate(    w,    "index/index",    map[string]interface{}{"PageTitle": "首页", "Name": "sqrt_cat", "Age": 25},  )}// newsfunc 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 自己指定要渲染的模板名,省的一团乱。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    php IP转换整形(ip2long)的详解
    下一条:
    php MYSQL 数据备份类
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客