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
}
}
------
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello</title>
</head>
<body>
<p>Hello {{.}}</p>
<p>Hello {{.Name}}</p>
<p>Hello {{.Hobby}}</p>
{{ range $song, $lele := .Zz }}
<p>小宝贝</p>
{{end}}
</body>
</html>
模版的初始化步骤:
渲染
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(通常用了构建局部变量)
自定义函数
函数 有一个或者2个返回值,当有两个返回值是最后一个值类型是 err
模版嵌套
template中嵌套其他的template。这个template可以是单独的文件,也可以是通过define定义的template。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello</title>
</head>
<body>
<p>Hello {{.}}</p>
<p>Hello {{.Name}}</p>
<p>Hello {{.Hobby}}</p>
{{ range $song, $lele := .Zz }}
<p>{{ $lele }}</p>
{{end}}
<hr>
<h1>嵌套template</h1>
<hr>
{{template "z1.tmpl"}}
<hr>
{{template "z2.tmpl"}}
</body>
</html>
{{ define "z2.tmpl" }}
<p>在 z2 中的内容 被你看到了<\p>
{{end}}
在引用嵌套模版时,如果嵌套模版是独立文件,要在渲染阶段加入对应的模版列表
func sayHello(w http.ResponseWriter, r *http.Request) {
// 解析指定文件生成模板对象
tmpl, err := template.ParseFiles("./hello.tmpl","./z1.tmpl")
if err != nil {
fmt.Println("create template failed, err:", err)
return
}
本文来自博客园,作者:萱乐庆foreverlove,转载请注明原文链接:https://www.cnblogs.com/leleyao/p/15763882.html

浙公网安备 33010602011771号