[关闭]
@aliasliyu4 2017-03-05T19:54:28.000000Z 字数 2670 阅读 1956

golang模版的使用

前言

大部分的编程语言都是库实现模版,也是为了巩固mvc模式下服务端的统治地位,模版是如此的重要它甚至能够检验一个语言的成功和失败。然后,如今的现状是,单页应用大行其道,模版的使用已经变的越来越少。可能比较牢不可破的场景还是在生产邮件实体的时候。这篇文章中,我会使用一个例子去介绍如何用golang的template包生成基于定义在文件中的模版文件生成邮件实体。尽力去展现这个包中最常用的一些特性。

golang 代码:

  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "os"
  6. "time"
  7. )
  8. type Account struct {
  9. FirstName string
  10. LastName string
  11. }
  12. type Purchase struct {
  13. Date time.Time
  14. Description string
  15. AmountInCents int
  16. }
  17. type Statement struct {
  18. FromDate time.Time
  19. ToDate time.Time
  20. Account Account
  21. Purchases []Purchase
  22. }
  23. func formatAsDate(t time.Time) string {
  24. year, month, day := t.Date()
  25. return fmt.Sprintf("%d/%d/%d", day, month, year)
  26. }
  27. func formatAsDollars(valueInCents int) (string, error) {
  28. dollars := valueInCents / 100
  29. cents := valueInCents % 100
  30. return fmt.Sprintf("$%d.%2d", dollars, cents), nil
  31. }
  32. func urgentNote(acc Account) string {
  33. return fmt.Sprintf("You have earned 100 vip points that can be used for purchases")
  34. }
  35. func hello() string {
  36. return fmt.Sprintf("hello word!")
  37. }
  38. func createMockStatement() Statement {
  39. return Statement{
  40. FromDate: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
  41. ToDate: time.Date(2017, 2, 1, 0, 0, 0, 0, time.UTC),
  42. Account: Account{
  43. FirstName: "alias",
  44. LastName: "liyu4",
  45. },
  46. Purchases: []Purchase{
  47. Purchase{
  48. Date: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
  49. Description: "dell ultrasharp 24 monitor",
  50. AmountInCents: 23026,
  51. },
  52. Purchase{
  53. Date: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
  54. Description: "macbook air",
  55. AmountInCents: 88821,
  56. },
  57. },
  58. }
  59. }
  60. func main() {
  61. fmap := template.FuncMap{
  62. "formatAsDollars": formatAsDollars,
  63. "formatAsDate": formatAsDate,
  64. "urgentNote": urgentNote,
  65. "hello": hello,
  66. }
  67. t, err := template.New("email.tmpl").Funcs(fmap).ParseFiles("email.tmpl")
  68. if err != nil {
  69. panic(err)
  70. }
  71. //Execute applies a parsed template to the specified data object,
  72. //writing the output to wr. If an error occurs executing the template or writing its output,
  73. //execution stops, but partial results may already have been written to the output writer.
  74. //A template may be executed safely in parallel.
  75. if err := t.Execute(os.Stdout, createMockStatement()); nil != err {
  76. panic(err)
  77. }
  78. }

这段代码中最重要的部分是数据结构和main函数,其他的函数唯一的目的是展示从模版中调用不同的办法。

模版文件 email.tmpl:

  1. {{with .Account -}}
  2. Dear {{.FirstName}} {{.LastName}},
  3. {{- end}}
  4. Below are your account statement details for period from {{.FromDate | formatAsDate}} to {{.ToDate | formatAsDate}}.
  5. {{if .Purchases -}}
  6. Your purchases:
  7. {{- range .Purchases }}
  8. {{ .Date | formatAsDate}} {{ printf "%-20s" .Description }} {{.AmountInCents | formatAsDollars -}}
  9. {{- end}}
  10. {{- else}}
  11. You didn't make any purchases during the period.
  12. {{- end}}
  13. {{$note := urgentNote .Account -}}
  14. {{if $note -}}
  15. Note: {{$note}}
  16. {{- end}}
  17. Best Wishes,
  18. Customer Service

输出:

  1. Dear alias liyu4,
  2. Below are your account statement details for period from 1/1/2017 to 1/2/2017.
  3. Your purchases:
  4. 1/1/2017 dell ultrasharp 24 monitor $230.26
  5. 1/1/2017 macbook air $888.21
  6. Note: You have earned 100 vip points that can be used for purchases
  7. Best Wishes,
  8. Customer Service

原文: http://goinbigdata.com/example-of-using-templates-in-golang/

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注