Go学习:template模板使用(一)

入门示例

package main

import (
    "html/template"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        t, err := template.ParseFiles("tpl/hello.html") //创建一个模板
        if err != nil {
            panic(err.Error())
        }
        user := map[string]string{
            "name": "li",
        }
        e := t.Execute(w, user) //执行模板,并通过w输出
        if e != nil {
            panic(e.Error())
        }
    })
    log.Fatal(http.ListenAndServe(":9777", nil))
}

hello.html文件

<!DOCTYPE html>
<html lang="en">
<body>
    {{.}}
    <h1>HELLO WORLD</h1>
</body>
</html>

前面的html文件中使用了一个template的语法{{.}},这部分是需要通过go的template引擎进行解析,然后替换成对应的内容。
在go程序中,handler函数中使用template.ParseFiles(“tpl/hello.html”),它会自动创建一个模板(关联到变量t上),并解析一个或多个文本文件(不仅仅是html文件),解析之后就可以使用Execute(w,data)去执行解析后的模板对象,执行过程是合并、替换的过程。

template 数据绑定

template 动态数据如何表示? 例如上面的{{.}}中的.会替换成当前对象”user”,并和其它纯字符串内容进行合并,最后写入w中。
template 数据展示常用方法

# 渲染数据可以是go的所有类型
# 渲染数据本身
{{ . }}
# 自定义变量
{{ $var = . }}

# struct
# 大写字母开头属性Field 
{{ .Field }}
# 嵌套struct时的 属性Field1
{{ .Field.Field1 }}
# 变量为struct时的 属性Field
{{ $x = . }}
{{ $x.Field }}
# 方法
{{ .Method }}
# 嵌套struct的方法
{{ .Field.Method }}
# 嵌套struct的map中struct的方法
{{ .Field.Key.Method }}

# map
# 键名
{{ .key }}
# struct中map
{{ .Field.key }}
# 变量的struct中map
{{ $x = . }}
{{ $x.Field.key }}

# 函数
{{ funName . }}
# 注释
{{/* comment */}}
{{- /* comment */ -}}

# 默认输出,效果 fmt.Print(pipeline)
{{ pipeline }}

# 流程控制
{{if pipeline}} T1 {{end}}
{{if pipeline}} T1 {{else}} T0 {{end}}
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
{{with pipeline}} T1 {{end}}
{{with pipeline}} T1 {{else}} T0 {{end}}

# 循环
# array, slice, map, or channel
{{range pipeline}} T1 {{end}}
{{range pipeline}} T1 {{else}} T0 {{end}}

# 嵌套关联
{{template "name"}}
# 当前模板引入其他模板,并且传递数据
{{template "name" pipeline}}
# 等价声明和执行 {{define "name"}} T1 { {end}}  & {{template "name" pipeline}}
{{block "name" pipeline}} T1 {{end}} 
本作品采用《CC 协议》,转载必须注明作者和本文链接
Luson
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!