您的位置 首页 golang

golang template 模板_v0.1.0


1.模板是什么

这里的模板是一种基于数据的文本输出,Go语言的模板与大多数语言一样,是用 “{{” 和 “}}” 来做占位符,{{ }} 里可以是表达式,也可以是变量 ,不在“{{”和“}}”的文本原样输出。。
一个简单的实例

{{.Count }} items are made of {{ .Material}} 

Count和Material 分别是变量,假设已经赋值为了 Count:2110,Material:“plastic”.这个时候模板渲染出来的文本就是

2110 items are made of plastic

更加复杂一点的实例如下{{}}包含了逻辑表达式和函数,这里面包含逻辑判断if ,and,not,以及函数eq,和empty, “.Values.service.type”最终的结果是一个变量的值。 这里不用了解这一段渲染的结果,暂时只用看看样子感受一下就行了。

 {{- if and (eq .Values.service.type "LoadBalancer") (not (empty .Values.service.loadBalancerIP)) }}  loadBalancerIP: {{ .Values.service.loadBalancerIP }} {{- end }}

如果你有其他语言基础你就知道,golang的template 类似python的Jinja2,PHP的smarty,nodejs的jade,J2ee的Freemarker和velocity

2. 哪些地方会使用

  1. helm chart,有一个专门的目录是templates这是chart用来写各个k8s组建具体实现的地方,这里使用了很多。
  2. html中也会使用,golang中有"html/template"。
  3. 其他数据驱动,需要生成文本的地方。

3.简单golang模板的实例

package mainimport (    "os"    "text/template")type Inventory struct {    Material string    Count    uint}func main() {    cup := Inventory{"plastic", 2110}    tmpl, err := template.New("test").Parse("{{.Count }} items are made of {{ .Material}}")    if err != nil {        panic(err)    }    err = tmpl.Execute(os.Stdout, cup)    if err != nil {        panic(err)    }}

主要有三个步骤

  1. 创建模板 ,对应代码中的template.New("test")
  2. 加载分析模板字符串,对应代码中的 .Parse("{{.Count }} items are made of {{ .Material}}")
  3. 执行渲染模板到某处,这里使用 tmpl.Execute(os.Stdout, cup) ,将cup中变量渲染到标准输出中。

v1.0.0中加入这两块内容。
详细指南
高级用法


文章来源:智云一二三科技

文章标题:golang template 模板_v0.1.0

文章地址:https://www.zhihuclub.com/6593.shtml

关于作者: 智云科技

热门文章

网站地图