golang text/template讲解概述运行过程要求遍历structtext 和spacesActionsArgumentsPipelineVariablesPilelines和Variables例子FunctionsExamples更多
概述
text/template实现基于数据的文本化输出。功能和jsp、blade.php(laravel)一样,用于动态生成文件,只不过golang用于生产HTML的模块为html/template1
运行过程
将template模板应用于结构化的数据,使用注解语法引用数据结构中的元素(struct中的feild或map中的key)并显示它们的值。template在执行过程中遍历数据结构并且设置当前光标(英文句号“.”标识)标识当前位置的元素(值)
一旦解析,模板可以安全地并行执行,但是如果并行执行共享Writer,则输出可以是交错的。
要求
template的文本必须为UTF-8编码。注解语法必须由“{ {”和“}}”分隔,不在“{ {”和“}}”的文本原样输出。一般来说注解语法不用另起一行,可以和非注解文本同行,不过如果是动态注释的话,注解语法还是建议另起一行。
遍历struct
type Inventory struct {
Material string
Count uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{ {.Count}} items are made of { {.Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }
上面的例子中模板test变量sweaters中的Count和Material域,“.Count”中的“.”标识sweaters根元素
执行结果
➜ template git:(master) ✗ go run text_template.go
17 items are made of wool%
text 和spaces
虽然所有在“{ {}}”控制注解之外的文本会默认一分不差地复制到输出中,但是如果“{ {”紧接着跟随“—”和“ ”的话,那么“{ {”之前的文本中的空白(空格、换行符、回车符、制表符)会被移除。对应的,“ -}}”表示移除之后文本中的空白。
例如上面例子,稍作修改:
package main
import (
"os"
"text/template"
)
type Inventory struct {
Material string
Count uint
}
func main(){
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{ {.Count -}} items are made of { {- .Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }
}
执行结果:
➜ template git:(master) ✗ go run text_template.go
17items are made