【Golang】go template基本使用

go template是个模板替换的包,如果是普通text就使用text/template,如果是html还有html/template,其实有过jsp开发经验的人对这个东西应该很容易上手,它比那些jstl表达式要简单很多。下面看看基本使用:

package main

import (
    "text/template"
	"os"
)

type ZHAO struct {
	Name string
	Email string
	Array []string
}

func main() {
	zhao_1 := ZHAO{"zhao", "[email protected]", []string{"1","12","12345"}}
	zhao_2 := ZHAO{"lurongming", "[email protected]", []string{"he","llo","world"}}
	t, _ := template.New("example").Parse("hello {{.}}\n")
	t.Execute(os.Stdout, zhao_1)
	t.Execute(os.Stdout, zhao_2)
}

输出结果为:

hello {zhao 823952051@qq.com [1 12 12345]}
hello {lurongming rongming_lu@163.com [he llo world]}

当然如果想对数据进行更复杂点的操作,可以通过独立的pipeline来处理数据。下面说一个复杂一点的用函数处理的例子:

package main

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

type ZHAO struct {
	Name string
	Email string
	Array []string
}

func show(zhao ZHAO) string {
	return fmt.Sprintf("hello %s! an email: %s.", zhao.Name, zhao.Email)
}

func main() {

	zhao_1 := ZHAO{"zhao", "[email protected]", []string{"1","12","12345"}}
	zhao_2 := ZHAO{"lurongming", "[email protected]", []string{"he","llo","world"}}
	t := template.New("example")
	t = t.Funcs(template.FuncMap{"fun": show})
	t, _ = t.Parse("{{.|fun}}\n")
	t.ExecuteTemplate(os.Stdout, "example", zhao_1)
	t.ExecuteTemplate(os.Stdout, "example", zhao_2)
}

输出结果为:

hello zhao! an email: [email protected].
hello lurongming! an email: [email protected].
发布了370 篇原创文章 · 获赞 14 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/105356205