首页 > 编程语言 > 详细

Go语言从零学习template

时间:2015-05-15 10:48:56      阅读:268      评论:0      收藏:0      [点我收藏+]

1、简单实例

package main

import (
	"os"
	"text/template"
)

func main() {
	const xichen = `Hello World {{.}}`
	M := template.New("")
	M.Parse(di)
	M.Execute(os.Stdout, "曦晨")
}

2、循环使用

package main

import (
	"os"
	"text/template"
)

func main() {
	const 曦晨 = `{{range .}}Hello World :{{.}}
{{end}}`
	var list []string = []string{"曦晨", "李四", "张三"}
	M := template.New("")
	M.Parse(曦晨)
	M.Execute(os.Stdout, list)
}

3、结构体使用

package main

import (
	"os"
	"text/template"
)

type x struct {
	A姓名, B级别, C性别 string
}

const M = `姓名:{{.A姓名}}
级别:{{.B级别}}
性别:{{.C性别}}
`

func main() {
	var info = x{"曦晨", "1", "男"}
	tm := template.New("")
	tm.Parse(M)
	tm.Execute(os.Stdout, info)
}
4、条件语句使用

package main

import (
	"os"
	"text/template"
)

type x struct {
	A姓名, B级别, C性别 string
}

const M = `{{range .}}{{if .B级别}}姓名:{{.A姓名}}  性别:{{.C性别}}{{end}}
{{end}}`

func main() {
	var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}, {"曦love晨", "", "男love女"}}
	t := template.New("")
	template.Must(t.Parse(M))
	t.Execute(os.Stdout, di)
}
5、变量使用

package main

import (
	"os"
	"text/template"
)

type x struct {
	A姓名, B级别, C性别 string
}

const M = `{{range $k,$v := .}}信息:{{$v.A姓名}}
{{end}}`

func main() {
	var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}}
	t := template.New("")
	t.Parse(M)
	t.Execute(os.Stdout, di)
}
6、函数的使用

package main

import (
	"os"
	"text/template"
)

type x struct {
	A姓名, B级别, C性别 string
}

const M = `{{range $k,$v := .}}{{$k|Func|print}}{{$v.A姓名}}   // "|"作用相当于管道,用来传值
{{end}}`

func main() {
	var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}}
	Func := template.FuncMap{"Func": ce}   //把定义的函数实例
	t := template.New("")
	t.Funcs(Func)    //注册要使用的函数
	t.Parse(M)
	t.Execute(os.Stdout, di)
}

func ce(i int) string {
	return "姓名:"
}


Go语言从零学习template

原文:http://blog.csdn.net/fyxichen/article/details/45740143

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!