golang-gin(一) 模版的应用和入门


golang template 包 分为 text/template 和 html/template 两者内容基本相似。

一体式web 系统指页面也通过后端应用系统来进行渲染(利用数据根据模版动态填充页面内容)。

package main
import(
	"net/http"
	"fmt"
	"html/template"
)

type UserInfo struct{
	Name string
	Hobby string
	Zz []string
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	// 解析指定文件生成模板对象
	tmpl, err := template.ParseFiles("./hello.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
    zz := []string{
		"zz",
		"sdf",
		"sdfsdfs",
	}
	user := UserInfo{
		Name:   "乐乐王子",
		Hobby: "恐龙",
		Zz: zz,
	}
	// 利用给定数据渲染模板,并将结果写入w
	tmpl.Execute(w, user)
}


func main() {
	http.HandleFunc("/", sayHello)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}




------






    
    
    
    Hello


    

Hello {{.}}

Hello {{.Name}}

Hello {{.Hobby}}

{{ range $song, $lele := .Zz }}

小宝贝

{{end}}

模版的初始化步骤:

渲染

func (t *Template) Parse(src string) (*Template, error) 从
func ParseFiles(filenames ...string) (*Template, error)    从文件常用
func ParseGlob(pattern string) (*Template, error)      从字符串

填充

func (t *Template) Execute(wr io.Writer, data interface{}) error
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

template 支持的功能

取值  {{ . }}

固定取值 {{ .Name }}

赋值语句 pipeline 

注释 {{/* a comment */}}

去空格 {{- a comment -}}

变量 $arg = {{ .Name }}

判断 {{ if pipeline }} {{end}}

循环  range with(通常用了构建局部变量)