Golang 页面模板之模板中如何插入数据,输出嵌套字段内容?以及神奇的减号“-”,如何去掉Go Template生成的标签换行符

前端之家收集整理的这篇文章主要介绍了Golang 页面模板之模板中如何插入数据,输出嵌套字段内容?以及神奇的减号“-”,如何去掉Go Template生成的标签换行符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


/root/code/go/src/contoso.org/hello/index.html

<!DOCTYPE html>
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{range .Emails}}
<li>{{.}}</li>
{{end}}
</ul>
<ul>
{{with .Friends}}
{{range .}}
<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{end}}
{{end}}
</ul>
</div>
</body>
</html>

/root/code/go/src/contoso.org/hello/main.go

package main

import (
"html/template"
"net/http"
)

type Friend struct {
Fname string
Age int
Mobile string
}

type Person struct {
UserName string
Emails []string
Friends []*Friend
}

func main() {
http.HandleFunc("/",load)
http.ListenAndServe(":9090",nil)
}

func load(w http.ResponseWriter,r *http.Request) {
tim := Friend{Fname: "Tim",Age: 25,Mobile: "13620052000"}
jack := Friend{Fname: "Jack",Age: 28,Mobile: "13520172000"}
tom := Friend{Fname: "Tom",Age: 19,Mobile: "13512345000"}
p := Person{UserName: "Jason",
Emails: []string{"jason@163.com","jason@hotmail.com"},
Friends: []*Friend{&tim,&jack,&tom}}
t,_ := template.ParseFiles("index.html")
t.Execute(w,p)
}


模板格式处理如下,注意这个神奇的“-”符号,它的位置可以写在花括号内部的前后:

<!DOCTYPE html>
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{range .Emails -}}
<li>{{.}}</li>
{{- end}}
</ul>
<ul>
{{with .Friends -}}
{{range . -}}

<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{- end}}
{{- end}}

</ul>
</div>
</body>
</html>

神奇的减号“-”,去掉Go Template生成标签换行符:

<!DOCTYPE html>
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{- range .Emails}}
<li>{{.}}</li>
{{- end}}
</ul>
<ul>
{{- with .Friends}}
{{- range .}}
<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{- end}}
{{- end}}

</ul>
</div>
</body>

</html>

原文链接:https://www.f2er.com/go/188315.html

猜你在找的Go相关文章