golang text/template

https://juejin.im/post/5c403b98f265da612d1984c9

template包是数据驱动的文本输出模板,即在写好的模板中填充数据

模板

模板使用流程:

  • 定义模板
  • 解析模板
  • 数据驱动模板
package main

import (
    "os"
    "text/template"
)

func main() {
    //数据
    name := "Tom"
    //定义模板
    muban := "hello, {{.}}"
    //解析模板
    tmpl, err := template.New("test").Parse(muban)
    if err != nil {
        panic(err)
    }
    //数据驱动模板
    err = tmpl.Execute(os.Stdout, name)
    if err != nil {
        panic(err)
    }
}

output

hello, Tom

传入struct

实例

package main

import (
    "os"
    "text/template"
)

type Student struct {
    Name string
}

func main() {
    tom := Student{"Tom"}
    // name := "Tom"
    muban := "hello, {{.Name}}"
    tmpl, err := template.New("test").Parse(muban)
    if err != nil {
        panic(err)
    }
    err = tmpl.Execute(os.Stdout, tom)
    if err != nil {
        panic(err)
    }
}

output

hello, Tom

{{和}}之间的.代表传入模板的数据,根据传入的数据不同渲染不同的内容。
.可以代表golang中的任何类型,struct、map等。
{{和}}之间的内容统称为action,一共有两种:

  • 数据求值
  • 控制结构
    action求值的结果会直接复制到模板中,控制结构和我们写 Go 程序差不多,也是条件语句、循环语句、变量、函数调用等等...
    将模板成功解析(Parse)后,可以安全地在并发环境中使用,如果输出到同一个 io.Writer 数据可能会重叠(因为无法保证并发执行的先后顺序)。

Actions

注释

执行时会忽略。可以多行。注释不能嵌套,并且必须紧贴分界符始止

语法

{{/*comment*/}}

示例

package main

import (
    "os"
    "text/template"
)

func main() {
    name := "Tom"
    muban := "hello, {{.}}{{/*This is a comment of test template*/}}"
    tmpl, err := template.New("test").Parse(muban)
    if err != nil {
        panic(err)
    }
    err = tmpl.Execute(os.Stdout, name)
    if err != nil {
        panic(err)
    }
}

output

hello, Tom

裁剪空格

// 裁剪 content 前后的空格
{{- content -}}

// 裁剪 content 前面的空格
{{- content }}

// 裁剪 content 后面的空格
{{ content -}}

详细用法见下文
模板

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。