资讯专栏INFORMATION COLUMN

go html/template 模板的使用实例

SegmentFault / 2061人阅读

摘要:从模板文件构建首页新闻手动的指定每一个模板文件,在一些场景下难免难以满足需求,我们可以使用通配符正则匹配载入。

从字符串载入模板

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

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. {{ .PageTitle }}
  3. {{ end }}
views/footer.html

</>复制代码

  1. {{ define "footer" }}
  2. {{ end }}
views/index/index.html

</>复制代码

  1. {{ define "index/index" }}
  2. {{/*引用其他模板 注意后面的 . */}}
  3. {{ template "header" . }}
  4. hello, {{ .Name }}, age {{ .Age }}
  5. {{ template "footer" . }}
  6. {{ end }}
views/news/index.html

</>复制代码

  1. {{ define "news/index" }}
  2. {{ template "header" . }}
  3. {{/* 页面变量定义 */}}
  4. {{ $pageTitle := "news title" }}
  5. {{ $pageTitleLen := len $pageTitle }}
  6. {{/* 长度 > 4 才输出 eq ne gt lt ge le */}}
  7. {{ if gt $pageTitleLen 4 }}
  8. {{ $pageTitle }}

  9. {{ end }}
  10. {{ $c1 := gt 4 3}}
  11. {{ $c2 := lt 2 3 }}
  12. {{/*and or not 条件必须为标量值 不能是逻辑表达式 如果需要逻辑表达式请先求值*/}}
  13. {{ if and $c1 $c2 }}
  14. 1 == 1 3 > 2 4 < 5

  15. {{ end }}
    • {{ range .List }}
    • {{ $title := .Title }}
    • {{/* .Title 上下文变量调用 func param1 param2 方法/函数调用 $.根节点变量调用 */}}
    • {{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}
    • {{end}}
  16. {{/* !empty Total 才输出*/}}
  17. {{ with .Total }}
  18. 总数:{{ . }}
  19. {{ end }}
  20. {{ template "footer" . }}
  21. {{ end }}
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. // render template with tplName index
  11. _ = tpl.ExecuteTemplate(
  12. os.Stdout,
  13. "index/index",
  14. map[string]interface{}{
  15. PageTitle: "首页",
  16. Name: "big_cat",
  17. Age: 29,
  18. },
  19. )
  20. // render template with tplName index
  21. _ = tpl.ExecuteTemplate(
  22. os.Stdout,
  23. "news/index",
  24. map[string]interface{}{
  25. "PageTitle": "新闻",
  26. "List": []struct {
  27. Title string
  28. CreatedAt time.Time
  29. }{
  30. {Title: "this is golang views/template example", CreatedAt: time.Now()},
  31. {Title: "to be honest, i don"t very like this raw engine", CreatedAt: time.Now()},
  32. },
  33. "Total": 1,
  34. "Author": "big_cat",
  35. },
  36. )
template.ParseGlob

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

</>复制代码

  1. 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服务器

结合html/template模板库和net/http实现一个可以使用模板渲染并返回html页面的web服器。

</>复制代码

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

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/53928.html

相关文章

  • 【JS实用技巧】优化动态创建元素方式,让代码更加优雅且利于维护

    摘要:更好的方案模板分离原则模板分离原则将定义模板的那一部分,与的代码逻辑分离开来,让代码更加优雅且利于维护。 showImg(https://segmentfault.com/img/bVJ73t?w=800&h=316); 引言 在前端开发中,经常需要动态添加一些元素到页面上。那么如何通过一些技巧,优化动态创建页面元素的方式,使得代码更加优雅,并且更易于维护呢?接下来我们通过研究一些实例...

    JeOam 评论0 收藏0
  • 【JS实用技巧】优化动态创建元素方式,让代码更加优雅且利于维护

    摘要:更好的方案模板分离原则模板分离原则将定义模板的那一部分,与的代码逻辑分离开来,让代码更加优雅且利于维护。 showImg(https://segmentfault.com/img/bVJ73t?w=800&h=316); 引言 在前端开发中,经常需要动态添加一些元素到页面上。那么如何通过一些技巧,优化动态创建页面元素的方式,使得代码更加优雅,并且更易于维护呢?接下来我们通过研究一些实例...

    hqman 评论0 收藏0
  • Webpack 4 和单页应用入门

    摘要:但由于和技术过于和复杂,并没能得到广泛的推广。但是在浏览器内并不适用。依托模块化编程,的实现方式更为简单清晰,一个网页不再是传统的类似文档的页面,而是一个完整的应用程序。到了这里,我们的主角登场了年此处应有掌声。和差不多同期登场的还有。 Github:https://github.com/fenivana/w...webpack 更新到了 4.0,官网还没有更新文档。因此把教程更新一下...

    Zoom 评论0 收藏0
  • Angular directive 实例详解

    摘要:方法三使用调用父作用域中的函数实例地址同样采用了缺省写法,运行之后,弹出窗口布尔值或者字符,默认值为这个配置选项可以让我们提取包含在指令那个元素里面的内容,再将它放置在指令模板的特定位置。 准备代码,会在实例中用到 var app = angular.module(app, []); angular指令定义大致如下 app.directive(directiveName, functi...

    Jiavan 评论0 收藏0
  • Angular directive 实例详解

    摘要:方法三使用调用父作用域中的函数实例地址同样采用了缺省写法,运行之后,弹出窗口布尔值或者字符,默认值为这个配置选项可以让我们提取包含在指令那个元素里面的内容,再将它放置在指令模板的特定位置。 准备代码,会在实例中用到 var app = angular.module(app, []); angular指令定义大致如下 app.directive(directiveName, functi...

    BLUE 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<