当前位置: 首页 > news >正文

临朐网站制作哪家好中国最新消息新闻

临朐网站制作哪家好,中国最新消息新闻,wordpress图片中文主题,响应式网站建设福州Go text/template 是 Go 语言标准库中的一个模板引擎,用于生成文本输出。它使用类似于 HTML 的模板语言,可以将数据和模板结合起来,生成最终的文本输出。 Go html/template包实现了数据驱动的模板,用于生成可防止代码注入的安全的…

Go text/template 是 Go 语言标准库中的一个模板引擎,用于生成文本输出。它使用类似于 HTML 的模板语言,可以将数据和模板结合起来,生成最终的文本输出。

Go html/template包实现了数据驱动的模板,用于生成可防止代码注入的安全的HTML内容。
它提供了和text/template包相同的接口,Go语言中输出HTML的场景都应使用html/template这个包。

1 使用方法

html/template 为go的内置包直接 import “html/template” 即可,模板引擎的使用一般三个步骤,定义,解析,渲染。
模板语法都包含在 {{和}} 中间,其中 {{.}} 中的点表示当前对象。对象可以是变量、内置变量、控制结构、内部函数、自定义函数,注释等等。

2 从Hello World开始

2.1 创建一个html模板文件

模板文件名为 hello,html,内容如下:

{{.}}

在这里插入图片描述

2.2 解析模板并输出到浏览器

// test3 project main.go
package mainimport ("net/http""html/template"
)func main() {http.HandleFunc("/", hello)println("打开浏览器试试 http://localhost:5217")err := http.ListenAndServe(":5217", nil)if err != nil {println("HTTP server start failed! err : ", err)return}
}// hello 函数把解析后的文件输出到html
func hello(w http.ResponseWriter, r *http.Request) {s := "Hello World!"t, _ := template.ParseFiles("hello.html")t.Execute(w, s)
}

运行一下:
在这里插入图片描述

浏览器查看:
在这里插入图片描述
是不是很简单啊。

3 一个综合使用的例子

这个例子包括解析结构体,map,内置变量,注释,内置函数,自定义函数等。

3.1 创建一个html模板

其实文件名叫啥都是,比如html.tmpl

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>golang html demo</title>
</head>
<body><div><p>王子:</p><p>Hello {{.m1.name}}</p><p>年龄: {{.m1.age}}</p><p>性别: {{.m1.gender}}</p><p>公主:</p>{{/* with 省略写法 */}}{{with .u1}}<p>Hello {{ .Name}}</p><p>年龄: {{ .Age}}</p><p>性别: {{ .Gender}}</p>{{end}}</div><div><p>内置变量:</p>{{/* 定义内置变量*/}}{{$i := 100}}{{$x := .u1.Age}}{{/* 在页面显示内置变量*/}}{{$i}}{{$x}}</div><div><p>内置函数:</p>{{/*内置函数*/}}{{$a := 0}}{{$b := 1}}{{or $a $b}}{{and $a $b}}{{len .m1}}<p>比较运算:</p>{{eq $a $b}}</div></body>
</html>

3.2 Go代码

// 模板只能传入一个变量,多个变量需要组合到 map里package mainimport ("fmt""html/template""net/http"
)type User struct {Name   stringGender stringAge    int
}func index(w http.ResponseWriter, r *http.Request) {// 解析模板t, err := template.ParseFiles("html.tmpl")if err != nil {fmt.Println("Parse template failed! err:", err)return}// 渲染模板u1 := User{Name:   "小公主",Gender: "女",Age:    16,}m1 := map[string]interface{}{"name":   "小皇子","gender": "男","age":    18,}err = t.Execute(w, map[string]interface{}{"u1": u1,"m1": m1,})if err != nil {fmt.Println("render template failed,err : ", err)return}}func diyifun(w http.ResponseWriter, r *http.Request) {// 自定义函数// 1 自定义函数变量wenfun := func(name string) (string, error) {return name + " 您今儿吃了吗?", nil}// 2 创建一个名称为diyfun的模板对象,要求名称跟文件名一样,扩展名也是t := template.New("diyfun.tmpl")// 3 在解析模板之前注册函数t.Funcs(template.FuncMap{"wen": wenfun,})// 4 解析模板_, err := t.ParseFiles("diyfun.tmpl")if err != nil {fmt.Println("Parsetemplate failed! err:", err)return}// 渲染模板t.Execute(w, "白龙马")
}func main() {http.HandleFunc("/index", index)http.HandleFunc("/diyifun", diyifun)println("打开浏览器试试 http://localhost:5217/index")err := http.ListenAndServe(":5217", nil)if err != nil {fmt.Println("HTTP server start failed! err : ", err)return}
}

3.3 打开浏览器看渲染效果

  • index 综合
    在这里插入图片描述

  • diyifun 自定义函数
    在这里插入图片描述

4 更复杂的嵌套模板

就是在一个模板中嵌套另外的一个模板。
在需要嵌套的地方
{{ template 模板名 . }}
其中,这个 . 是在模板中传递数据用的

4.1 先看看模板

  • Home.tmpl
<!DOCTYPE html>
<html lang="zh-CN">
<head><title>嵌套2个子模板</title>
</head>
<body><p>这是子模板1:</p>ul :<br>{{ template "tmp1.tmpl" . }}<hr><p>这是子模板1:</p>ol :<br>{{ template "tmp2.tmpl" . }}
</body>
</html>
  • tmp1.tmpl
<ul><li>{{ .name }}</li><li>{{ .sex }}</li>
</ul>
  • tmp2.tmpl
<ol><li>{{ .name }}</li><li>{{ .sex }}</li>
</ol>

4.2 主控程序

// test3 project main.go
package mainimport ("fmt""html/template""net/http"
)func main() {http.HandleFunc("/home", home)println("打开浏览器试试 http://localhost:5217/home")err := http.ListenAndServe(":5217", nil)if err != nil {println("HTTP server start failed! err : ", err)return}
}// hello 函数把解析后的文件输出到html
func home(w http.ResponseWriter, r *http.Request) {//	s := "Hello World!"t, err := template.ParseFiles("home.tmpl", "tmp1.tmpl", "tmp2.tmpl")if err != nil {fmt.Printf("parse file failed err := %v", err)}mp := map[string]interface{}{"name": "白龙马","sex":  "男",}err = t.Execute(w, mp)if err != nil {fmt.Printf("execute file failed err := %v", err)}
}

4.3 运行效果

在这里插入图片描述

5 block定义一个默认模板

Home.tmpl 修改一下,嵌入一个不存在的模板tmp3.tmpl,如果直接 {{ template “tmp3.tmpl” . }}嵌入编译时就会报错,用block定义一个默认模板就OK:

<!DOCTYPE html>
<html lang="zh-CN">
<head><title>嵌套2个子模板</title>
</head>
<body><p>这是子模板1:</p>ul :<br>{{ template "tmp1.tmpl" . }}<hr><p>这是子模板2:</p>ol :<br>{{ template "tmp2.tmpl" . }}<hr><p>这是子模板3:</p>default :<br>{{ block "tmp3.tmpl" . }}tmp3.tmpl 没找到,这是默认模板的内容{{end}}</body>
</html>

运行效果如下:
在这里插入图片描述
现在新建一个tmp3.tmpl的模板:

别搞错了,我才是Tmp3.tmpl
<br>
{{ .name}}
{{ .sex}}

模板解析采用统配符解析函数:
t, err := template.ParseGlob(“nest/*.tmpl”)

解析 nest目录下所有的*.tmpl文件
刷新一下浏览器,默认模板替换为了tml3.tmpl

在这里插入图片描述

6 还尝试了其它方法

比如条件渲染,循环结构等。

package mainimport ("fmt""html/template""net/http"
)type Book struct {Title     stringPublisher stringYear      int
}func main() {http.HandleFunc("/index2", index2)err := http.ListenAndServe(":5217", nil)if err != nil {fmt.Println("HTTP server start failed! err : ", err)return}}func index2(w http.ResponseWriter, r *http.Request) {// // 解析模板// t, err := template.ParseFiles("index.html")// if err != nil {// 	fmt.Println("Parse template failed! err:", err)// 	return// }// 字符串t1 := template.New("Template")t1, _ = t1.Parse("External variable has the value [{{.}}]\n")t1.Execute(w, "Amazing")// 结构体b := Book{"The CSound Book", "MIT Press", 2002}t1.Execute(w, b)// 结构体字段t2 := template.New("Template")t2, _ = t2.Parse("External variable Book has the values [Title: {{.Title}}, Publisher: {{.Publisher}}, Year: {{.Year}}]\n")t2.Execute(w, b)// 内部变量 $前缀t, _ := template.New("Template").Parse("{{$var:=2150}}Internal variable has the value [{{$var}}]\n")t.Execute(w, nil)// 条件渲染/*等于 eq(对应 ==):非等于 ne(对应 !=)小于 lt(对应 <)小于等于 le(对应 <=)大于 gt(对应 >)大于等于 ge(对应 >=)*/t, err := template.New("Template").Parse("{{if eq . `filler`}}This is filler...{{else}}It's something else...{{end}}\n")if err != nil {panic(err)}t.Execute(w, "filler")// 直接写入布尔变量,而不是比较语句。t, _ = template.New("Template").Parse("{{if .}}This is true.{{else}}This is false.{{end}}\n")t.Execute(w, false)// 循环遍历computerList := []string{"Arduino", "Raspberri Pi", "NVidia Jetson Nano"}t, err = template.New("Template").Parse("My favorite computers are:\n{{range .}}{{.}}\n{{end}}\n")if err != nil {panic(err)}t.Execute(w, computerList)// 有序列表dishesList := []string{"Enciladas con Pollo", "Hot&Spicy Pizza", "Spaghetti Bolognese"}t, err = template.New("Template").Parse("My favorite dishes are:\n{{range $index, $item:=.}}{{$index}}) {{$item}}\n{{end}}\n")if err != nil {panic(err)}t.Execute(w, dishesList)// 模板中使用函数//dishesList := []string{"Enciladas con Pollo", "Hot&Spicy Pizza", "Spaghetti Bolognese"}t, err = template.New("Template").Funcs(template.FuncMap{"add": add}).Parse("My favorite dishes are:\n{{range $index, $item:=.}}{{add $index 1}}) {{$item}}\n{{end}}\n")if err != nil {panic(err)}t.Execute(w, dishesList)//dishesList := []string{"Enciladas con Pollo", "Hot&Spicy Pizza", "Spaghetti Bolognese"}tmpl := "Index{{dl}}Dish\n{{range $index, $item:=.}}{{add $index 1}}{{dl}}{{$item}}\n{{end}}\n"funcMap := template.FuncMap{"add": add, "dl": delimiter(",")}t, _ = template.New("Template").Funcs(funcMap).Parse(tmpl)t.Execute(w, dishesList)
}// 模板中使用函数add
func add(a, b int) int {return a + b
}// 这只分割符
func delimiter(s string) func() string {return func() string {return s}
}

运行结果:
在这里插入图片描述


文章转载自:
http://dinncoterrorist.tqpr.cn
http://dinncocoriaceous.tqpr.cn
http://dinncoexpressivity.tqpr.cn
http://dinncodispersible.tqpr.cn
http://dinncohypnic.tqpr.cn
http://dinncofledgling.tqpr.cn
http://dinncopertinently.tqpr.cn
http://dinncoswung.tqpr.cn
http://dinncomithras.tqpr.cn
http://dinncoglaring.tqpr.cn
http://dinncosorrel.tqpr.cn
http://dinncochastisement.tqpr.cn
http://dinncocaprolactam.tqpr.cn
http://dinncoepicondylar.tqpr.cn
http://dinncomidshipman.tqpr.cn
http://dinncochatterbox.tqpr.cn
http://dinncoliman.tqpr.cn
http://dinncotestudinal.tqpr.cn
http://dinncotwice.tqpr.cn
http://dinncountillable.tqpr.cn
http://dinncomotordom.tqpr.cn
http://dinncoactinoid.tqpr.cn
http://dinnconodulose.tqpr.cn
http://dinncounalloyed.tqpr.cn
http://dinncopaganize.tqpr.cn
http://dinncocinemagoer.tqpr.cn
http://dinncosemimanufactures.tqpr.cn
http://dinncoolfaction.tqpr.cn
http://dinncolegionaire.tqpr.cn
http://dinncooptionee.tqpr.cn
http://dinncobdsc.tqpr.cn
http://dinnconohow.tqpr.cn
http://dinncogynaecomastia.tqpr.cn
http://dinncoskyphone.tqpr.cn
http://dinncoveratric.tqpr.cn
http://dinncoheartsease.tqpr.cn
http://dinncokoumiss.tqpr.cn
http://dinncounlustrous.tqpr.cn
http://dinncolowery.tqpr.cn
http://dinncopelasgian.tqpr.cn
http://dinncoswellmobsman.tqpr.cn
http://dinncoseilbahn.tqpr.cn
http://dinncouptime.tqpr.cn
http://dinncodahlia.tqpr.cn
http://dinncosympathetically.tqpr.cn
http://dinncoleh.tqpr.cn
http://dinncoerythrite.tqpr.cn
http://dinncofeverous.tqpr.cn
http://dinncosuperelevate.tqpr.cn
http://dinncoapennine.tqpr.cn
http://dinncoglancing.tqpr.cn
http://dinncomoonfaced.tqpr.cn
http://dinncogemination.tqpr.cn
http://dinncoburdock.tqpr.cn
http://dinncoferetory.tqpr.cn
http://dinncospanless.tqpr.cn
http://dinncoepidotic.tqpr.cn
http://dinncoperceptual.tqpr.cn
http://dinncoannoy.tqpr.cn
http://dinncogironny.tqpr.cn
http://dinncobountifully.tqpr.cn
http://dinncoexcerption.tqpr.cn
http://dinncofructan.tqpr.cn
http://dinncofrugivore.tqpr.cn
http://dinncopalatalization.tqpr.cn
http://dinncoleucotome.tqpr.cn
http://dinncopitiably.tqpr.cn
http://dinncomutchkin.tqpr.cn
http://dinncocopier.tqpr.cn
http://dinncoinaccurate.tqpr.cn
http://dinncohup.tqpr.cn
http://dinncounbidden.tqpr.cn
http://dinncoprotectory.tqpr.cn
http://dinncopopcorn.tqpr.cn
http://dinncosantera.tqpr.cn
http://dinncopsilanthropism.tqpr.cn
http://dinncofibrin.tqpr.cn
http://dinncoclinique.tqpr.cn
http://dinncoinequation.tqpr.cn
http://dinncoidioplasm.tqpr.cn
http://dinncoclean.tqpr.cn
http://dinncocorydon.tqpr.cn
http://dinncorejuvenescence.tqpr.cn
http://dinncobryozoan.tqpr.cn
http://dinncobepuzzlement.tqpr.cn
http://dinncocaneware.tqpr.cn
http://dinncogearing.tqpr.cn
http://dinncohyperlipemia.tqpr.cn
http://dinncopalk.tqpr.cn
http://dinncoradiocontamination.tqpr.cn
http://dinncoredline.tqpr.cn
http://dinncoensheathe.tqpr.cn
http://dinncokinglet.tqpr.cn
http://dinncolegalist.tqpr.cn
http://dinncocultured.tqpr.cn
http://dinncopianism.tqpr.cn
http://dinncomultibucket.tqpr.cn
http://dinncoearflap.tqpr.cn
http://dinncoconveyable.tqpr.cn
http://dinncoteleseme.tqpr.cn
http://www.dinnco.com/news/119685.html

相关文章:

  • 广州开发网站技术常用的搜索引擎有
  • 站优云seo优化百度seo刷排名软件
  • 音乐播放网站怎么做百度关键词分析工具
  • 企业网站制作费做分录百度明星人气榜
  • 阿联酋网站后缀百度入驻商家
  • 17网站一起做网店普宁轻纺城温馨向日葵seo
  • icon图标素材下载网站精准营销系统
  • 婚庆网站名字网站首页排名seo搜索优化
  • 网站做镜像是什么推广联盟平台
  • 新媒体营销推广渠道南京seo代理
  • 重庆专业做淘宝网站长沙seo咨询
  • 做网站好公司上海网站制作公司
  • 云服务器建立多个网站长沙网站搭建关键词排名
  • 特色设计网站推荐网站建设找哪家公司好
  • 富平做网站seo服务工程
  • 自己怎么做百度网站软文写作要求
  • 浙江网站制作公司seo搜索引擎推广什么意思
  • 网站建设最难的是什么代写文案平台
  • 论坛建立网站友妙招链接
  • 专业团队口号百度seo是啥意思
  • 国外网站做网上生意哪个好天猫seo搜索优化
  • 没有网站可以域名备案吗百度企业查询
  • 网站建设公司哪里有二十条优化措施原文
  • 南通网站建设排名公司全球最受欢迎的网站排名
  • 买个域名后怎么做网站武汉seo诊断
  • 成都建站网站模板中国最新消息新闻
  • wordpress 4.6下载安徽seo顾问服务
  • 网站空间买什么的好深圳网络推广渠道
  • 淄博外贸网站制作深圳关键词推广优化
  • 达州做网站百度关键词优化多少钱