golang text/template

栏目: Go · 发布时间: 4年前

内容简介:模板使用流程:

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 -}}

示例


以上所述就是小编给大家介绍的《golang text/template》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Thinking Recursively

Thinking Recursively

Eric S. Roberts / Wiley / 1986-1-17 / USD 85.67

The process of solving large problems by breaking them down into smaller, more simple problems that have identical forms. Thinking Recursively: A small text to solve large problems. Concentrating on t......一起来看看 《Thinking Recursively》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具