欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-30 15:23:10
从字符串载入模板 我们可以定义模板字符串,然后载入并解析渲染: template.new(tplname string).parse(tpl string)...

从字符串载入模板

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

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" }}
<!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 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 自己指定要渲染的模板名,省的一团乱。

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