模板函数
创建一个名字为name的模板
func New(name string) *Template
解析模板字符串
func (t *Template) Parse(text string) (*Template, error)
解析文件
func (t *Template) ParseFiles(filenames ...string) (*Template, error)
执行模板,将结果写入wr
func (t *Template) Execute(wr io.Writer, data interface{}) error
注册函数给模板,注册之后模板就可以通过名字调用外部函数
func (t *Template) Funcs(funcMap FuncMap) *Template
type FuncMap map[string]interface{}
对象解析
{{}}来包含需要在渲染时被替换的字段,{{.}}表示当前的对象
如果要访问当前对象的字段通过{{.FieldName}},但是需要注意一点:这个字段必须是导出的(字段首字母必须是大写的),否则在渲染的时候就会报错
import (
"html/template"
"log"
"os"
)
type User struct {
Name string
Age int
}
func main(){
tmpl,err := template.New("Demo").Parse("My name is {{.Name}}\n I am {{.Age}} year old")
if err!=nil {
log.Fatal("Parse error",err);
}
err = tmpl.Execute(os.Stdout,User{
Name :"bx",
Age :23,
})
if err!=nil {
log.Fatal("execute error",err);
}
}
{{range.}}{{end}}
import (
"html/template"
"os"
)
func main(){
slice := []string{"test1","test2"}
tmpl,_:= template.New("slice").Parse("{{range.}}{{.}}\n{{end}}")
tmpl.Execute(os.Stdout,slice)
}
pipeline/管道
pipeline 翻译过来可以称为管道或者流水线, pipeline运算的作用是将多个函数调用或者值串起来,从左往右执行,左边执行的结果会传递给右边,形成一个任务流水。
pipeline运算符:| (竖线)
语法格式:
command1 | command2 | command3 ...
command可以是一个值,也可以是一个函数。
例子1:
{{"<h1>www.tizi365.com</h1>" | html}}
这里意思就是将第一个字符串值传递给html函数。
eg:
func main(){
const temStr = `{{. | printf "%s"}}`
t := template.Must(template.New("demo").Parse(temStr))
t.Execute(os.Stdout, "hello world")
}
内置函数
函数名 | 函数调用格式 | 对应关系运算 | 说明 |
---|---|---|---|
eq | eq arg1 arg2 | arg1 == arg2 | arg1等于arg2则返回true |
ne | ne arg1 arg2 | arg1 != arg2 | arg1不等于arg2则返回true |
lt | lt arg1 arg2 | arg1 < arg2 | arg1小于arg2则返回true |
le | le arg1 arg2 | arg1 <= arg2 | arg1小于等于arg2则返回true |
gt | gt arg1 arg2 | arg1 > arg2 | arg1大于arg2则返回true |
ge | ge arg1 arg2 | arg1 >= arg2 | arg1大于等于arg2则返回true |
逻辑运算函数
函数名 | 函数调用格式 | 对应逻辑运算 | 说明 |
---|---|---|---|
and | and 表达式1 表达式2 | 表达式1 && 表达式2 | 表达式1和表达式2都为真的时候返回true |
or | or 表达式1 表达式2 | 表达式1 || 表达式2 | 表达式1和表达式2其中一个为真的时候返回true |
not | not 表达式 | !表达式 | 表达式为false则返回true, 反之返回false |
函数调用
import (
"html/template"
"os"
)
func foo(str string)(result string){
return "hello "+str
}
func main(){
t, _:= template.New("demo").Funcs(template.FuncMap{"foo":foo}).Parse("{{.|foo}}")
t.Execute(os.Stdout,"test")
}
参考
https://www.tizi365.com/archives/90.html
https://github.com/griffin702/ginana