golang text/template的基本用法

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

内容简介:golang text/template的基本用法下面一个例子涉及:其中 "{{- "和" -}}"的连字符含义是是否trim前/后的空格。

golang text/template的基本用法

下面一个例子涉及:

  1. 取值
  2. if 判断
    -. 数字值判断
    -. 字符串判断
    -. 布尔值判断
    -. 元素存在性判断
  3. range循环
package main

import (
    "os"
    "log"
    "text/template"
)

const templateText = `
    # GENERAL VALUE
    NAME: {{.Name}}
    # IF STRING
    {{if ne .Name "Bob"}}No, I'm Not Bob{{end}}

    # IF NUMERIC
    {{- if le .Age 30}}
    I am a senior one
    {{else}}
    I am a little one
    {{end}}

    # IF BOOLEAN
    {{- if .Boy}}
    It's a Boy 
    {{else}}
    It's a Girl
    {{end}}

    # RANGE
    {{- range $index, $friend := .Friends}}
    Friend {{$index}}: {{$friend}}
    {{- end}}

    # EXISTENCE
    {{- with .Gift -}}
    I have a gift: {{.}}
    {{else}}
    I have not a gift.
    {{end}}

`

func main() {
    type Recipient struct {
        Name        string
        Age         int
        Boy         bool
        Friends     []string
        Gift        string
    }
    
    recipient := Recipient{
        Name    : "Jack",
        Age     : 30,
        Friends : []string {"Bob", "Json"},
        Boy     : true,
    }

    t := template.Must(template.New("anyname").Parse(templateText))
    err := t.Execute(os.Stdout, recipient)
    if err != nil {
        log.Println("Executing template:", err)
    }
}

其中 "{{- "和" -}}"的连字符含义是是否trim前/后的空格。

运行结果:

$ go build main.go && ./main

    # GENERAL
    NAME: Jack
    No, I'm Not Bob

    # IF1
    I am a senior one
    

    # IF2
    It's a Boy 
    

    # RANGE
    Friend 0: Bob
    Friend 1: Json

    # GIFT
    I have not a gift.

详细文档请参阅: https://golang.org/pkg/text/template/#pkg-examples

里面有很多高级用法,包括自定义函数等。


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

查看所有标签

猜你喜欢:

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

MongoDB

MongoDB

Kristina Chodorow / O'Reilly Media / 2013-5-23 / USD 39.99

How does MongoDB help you manage a huMONGOus amount of data collected through your web application? With this authoritative introduction, you'll learn the many advantages of using document-oriented da......一起来看看 《MongoDB》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具