经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML » 查看文章
Go html/template 模板的使用实例详解
来源:jb51  时间:2019/6/3 8:40:00  对本文有异议

从字符串载入模板

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

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

  1. // 从字符串模板构建
  2. tplStr := `
  3. {{ .Name }} {{ .Age }}
  4. `
  5. // if parse failed Must will render a panic error
  6. tpl := template.Must(template.New("tplName").Parse(tplStr))
  7. tpl.Execute(os.Stdout, map[string]interface{}{Name: "big_cat", Age: 29})

从文件载入模板

模板语法

模板文件,建议为每个模板文件显式的定义模板名称: {{ define "tplName" }} ,否则会因模板对象名与模板名不一致,无法解析(条件分支很多,不如按一种标准写法实现),另展示一些基本的模板语法。

  • 使用 {{ define "tplName" }} 定义模板名
  • 使用 {{ template "tplName" . }} 引入其他模板
  • 使用 . 访问当前数据域:比如 range 里使用 . 访问的其实是循环项的数据域
  • 使用 $. 访问绝对顶层数据域

views/header.html

  1. {{ define "header" }}
  2. <!doctype html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport"
  7. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  9. <title>{{ .PageTitle }}</title>
  10. </head>
  11. {{ end }}
  12. views/footer.html
  13. {{ define "footer" }}
  14. </html>
  15. {{ end }}

views/index/index.html

  1. {{ define "index/index" }}
  2. {{/*引用其他模板 注意后面的 . */}}
  3. {{ template "header" . }}
  4. <body>
  5. <div>
  6. hello, {{ .Name }}, age {{ .Age }}
  7. </div>
  8. </body>
  9. {{ template "footer" . }}
  10. {{ end }}

views/news/index.html

  1. {{ define "news/index" }}
  2. {{ template "header" . }}
  3. <body>
  4. {{/* 页面变量定义 */}}
  5. {{ $pageTitle := "news title" }}
  6. {{ $pageTitleLen := len $pageTitle }}
  7. {{/* 长度 > 4 才输出 eq ne gt lt ge le */}}
  8. {{ if gt $pageTitleLen 4 }}
  9. <h4>{{ $pageTitle }}</h4>
  10. {{ end }}
  11.  
  12. {{ $c1 := gt 4 3}}
  13. {{ $c2 := lt 2 3 }}
  14. {{/*and or not 条件必须为标量值 不能是逻辑表达式 如果需要逻辑表达式请先求值*/}}
  15. {{ if and $c1 $c2 }}
  16. <h4>1 == 1 3 > 2 4 < 5</h4>
  17. {{ end }}
  18.  
  19. <div>
  20. <ul>
  21. {{ range .List }}
  22. {{ $title := .Title }}
  23. {{/* .Title 上下文变量调用 func param1 param2 方法/函数调用 $.根节点变量调用 */}}
  24. <li>{{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}</li>
  25. {{end}}
  26. </ul>
  27. {{/* !empty Total 才输出*/}}
  28. {{ with .Total }}
  29. <div>总数:{{ . }}</div>
  30. {{ end }}
  31. </div>
  32. </body>
  33. {{ template "footer" . }}
  34. {{ end }}
  35.  

template.ParseFiles

手动定义需要载入的模板文件,解析后制定需要渲染的模板名 news/index 。

  1. // 从模板文件构建
  2. tpl := template.Must(
  3. template.ParseFiles(
  4. "views/index/index.html",
  5. "views/news/index.html",
  6. "views/header.html",
  7. "views/footer.html",
  8. ),
  9. )
  10.  
  11. // render template with tplName index
  12. _ = tpl.ExecuteTemplate(
  13. os.Stdout,
  14. "index/index",
  15. map[string]interface{}{
  16. PageTitle: "首页",
  17. Name: "big_cat",
  18. Age: 29,
  19. },
  20. )
  21. // render template with tplName index
  22. _ = tpl.ExecuteTemplate(
  23. os.Stdout,
  24. "news/index",
  25. map[string]interface{}{
  26. "PageTitle": "新闻",
  27. "List": []struct {
  28. Title string
  29. CreatedAt time.Time
  30. }{
  31. {Title: "this is golang views/template example", CreatedAt: time.Now()},
  32. {Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
  33. },
  34. "Total": 1,
  35. "Author": "big_cat",
  36. },
  37. )
  38.  

template.ParseGlob

手动的指定每一个模板文件,在一些场景下难免难以满足需求,我们可以使用通配符正则匹配载入。

1、正则不应包含文件夹,否则会因文件夹被作为视图载入无法解析而报错

2、可以设定多个模式串,如下我们载入了一级目录和二级目录的视图文件

  1. // 从模板文件构建
  2. tpl := template.Must(template.ParseGlob("views/*.html"))
  3. template.Must(tpl.ParseGlob("views/*/*.html"))
  4. // render template with tplName index
  5. // render template with tplName index
  6. _ = tpl.ExecuteTemplate(
  7. os.Stdout,
  8. "index/index",
  9. map[string]interface{}{
  10. PageTitle: "首页",
  11. Name: "big_cat",
  12. Age: 29,
  13. },
  14. )
  15. // render template with tplName index
  16. _ = tpl.ExecuteTemplate(
  17. os.Stdout,
  18. "news/index",
  19. map[string]interface{}{
  20. "PageTitle": "新闻",
  21. "List": []struct {
  22. Title string
  23. CreatedAt time.Time
  24. }{
  25. {Title: "this is golang views/template example", CreatedAt: time.Now()},
  26. {Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
  27. },
  28. "Total": 1,
  29. "Author": "big_cat",
  30. },
  31. )

Web服务器

结合模板库和 Gin 实现一个可以使用模板渲染并返回 html 页面的 web 服务。

  1. package main
  2.  
  3. import (
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "time"
  8. )
  9.  
  10. var (
  11. htmlTplEngine *template.Template
  12. htmlTplEngineErr error
  13. )
  14.  
  15. func init() {
  16. // 初始化模板引擎 并加载各层级的模板文件
  17. // 注意 views/* 不会对子目录递归处理 且会将子目录匹配 作为模板处理造成解析错误
  18. // 若存在与模板文件同级的子目录时 应指定模板文件扩展名来防止目录被作为模板文件处理
  19. // 然后通过 view/*/*.html 来加载 view 下的各子目录中的模板文件
  20. htmlTplEngine = template.New("htmlTplEngine")
  21.  
  22. // 模板根目录下的模板文件 一些公共文件
  23. _, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*.html")
  24. if nil != htmlTplEngineErr {
  25. log.Panic(htmlTplEngineErr.Error())
  26. }
  27. // 其他子目录下的模板文件
  28. _, htmlTplEngineErr = htmlTplEngine.ParseGlob("views/*/*.html")
  29. if nil != htmlTplEngineErr {
  30. log.Panic(htmlTplEngineErr.Error())
  31. }
  32.  
  33. }
  34.  
  35. // index
  36. func IndexHandler(w http.ResponseWriter, r *http.Request) {
  37. _ = htmlTplEngine.ExecuteTemplate(
  38. w,
  39. "index/index",
  40. map[string]interface{}{"PageTitle": "首页", "Name": "sqrt_cat", "Age": 25},
  41. )
  42. }
  43.  
  44. // news
  45. func NewsHandler(w http.ResponseWriter, r *http.Request) {
  46. _ = htmlTplEngine.ExecuteTemplate(
  47. w,
  48. "news/index",
  49. map[string]interface{}{
  50. "PageTitle": "新闻",
  51. "List": []struct {
  52. Title string
  53. CreatedAt time.Time
  54. }{
  55. {Title: "this is golang views/template example", CreatedAt: time.Now()},
  56. {Title: "to be honest, i don't very like this raw engine", CreatedAt: time.Now()},
  57. },
  58. "Total": 1,
  59. "Author": "big_cat",
  60. },
  61. )
  62. }
  63.  
  64. func main() {
  65. http.HandleFunc("/", IndexHandler)
  66. http.HandleFunc("/index", IndexHandler)
  67. http.HandleFunc("/news", NewsHandler)
  68.  
  69. serverErr := http.ListenAndServe(":8085", nil)
  70.  
  71. if nil != serverErr {
  72. log.Panic(serverErr.Error())
  73. }
  74. }

注意 :模板对象是有名字属性的, template.New("tplName") ,如果没有显示的定义名字,则会使用第一个被载入的视图文件的 baseName 做默认名,比如我们使用 template.ParseFiles/template.ParseGlob 直接生成模板对象时,没有指定模板对象名,则会使用第一个被载入的文件,比如 views/index/index.html 的 baseName 即 index.html 做默认名,而后如果 tplObj.Execute 方法执行渲染时,会去查找名为 index.html 的模板,所以常用的还是 tplObj.ExecuteTemplate 自己指定要渲染的模板名,省的一团乱。

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号