【JSON2WEB】03 go的模板包html/template的使用

这篇具有很好参考价值的文章主要介绍了【JSON2WEB】03 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,内容如下:

{{.}}

【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

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

// test3 project main.go
package main

import (
	"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)
}

运行一下:
【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

浏览器查看:
【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone
是不是很简单啊。

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 main

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

type User struct {
	Name   string
	Gender string
	Age    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 综合
    【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

  • diyifun 自定义函数
    【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

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 main

import (
	"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 运行效果

【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

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>

运行效果如下:
【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone
现在新建一个tmp3.tmpl的模板:

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

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

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

【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone

6 还尝试了其它方法

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

package main

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

type Book struct {
	Title     string
	Publisher string
	Year      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
	}
}

运行结果:
【JSON2WEB】03 go的模板包html/template的使用,JSON2WEB,golang,html,iphone文章来源地址https://www.toymoban.com/news/detail-823439.html

到了这里,关于【JSON2WEB】03 go的模板包html/template的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • go语言模板处理包text/template详解

     本文对go语言内置模板处理包\\\"text/template\\\"常用操作汇总进行了详解,非常全面,一次搞定你的问题!还不收藏等啥呢! 目录 通用结构体定义 通用转换 1,基础操作 2,解析文件 3,自定义函数调用 4,循环遍历 5,语句、运算符、函数 6,变量与操作符

    2024年01月25日
    浏览(40)
  • 32 - 个人博客项目-03-公共模板-base.html

    新建公共模板: templates / base.html         (1). 继承bootstrap父级模板         (2). 标题         (3). css         (4). 导航栏         (5). 内容

    2024年02月10日
    浏览(31)
  • 【cobra】手写你的第一个命令行脚手架工具 | cobra整合go template通过终端以命令行方式生成.drone.yml 模板

    本次教程使用的开源框架如下: 名字 开源地址 作用 Cobra 命令行工具 https://github.com/spf13/cobra Aurora 字体颜色 https://github.com/logrusorgru/aurora go-zero go-z框架 模板功能 https://github.com/zeromicro/go-zero 本项目完整源码 :https://github.com/ctra-wang/cobra-gen-drone 概述 :Cobra 是一个 Golang 包,它

    2024年02月16日
    浏览(33)
  • go web框架 gin-gonic源码解读03————middleware

    今天打完游戏有空整理整理之前看的gin的中间件设计,go的中间件设计相较于前两站还是蛮简单,蛮容易看懂的,所以顺便把context也一起写一下。 中间件是现在web服务里统一化拓展最常用的功能,,他是为了在我们的web服务中实现一些可重复使用,可组合的功能方法、可以让

    2024年02月11日
    浏览(24)
  • Mind2Web: Towards a Generalist Agent for the Web 论文解读

    主页:https://osu-nlp-group.github.io/Mind2Web 训练集:https://huggingface.co/datasets/osunlp/Mind2Web 本文介绍了一个名为MIND2WEB的数据集,用于开发和评估Web通用代理,可以使用自然语言输入指令,使之可以在任何复杂的网站上执行操作。 前人缺陷: 现有的用于Web代理的数据集要么使用 模拟

    2024年02月08日
    浏览(34)
  • 浅谈WPF之控件模板Control Template和数据模板Data Template

    WPF不仅支持传统的Windows Forms编程的用户界面和用户体验设计,同时还推出了以模板为核心的新一代设计理念。在WPF中,通过引入模板,将数据和算法的“内容”和“形式”进行解耦。模板主要分为两大类:数据模板【Data Template】和控件模板【Control Template】 基本上,ControlT

    2024年02月03日
    浏览(27)
  • Web前端开发技术课程大作业: 关于美食的HTML网页设计——HTML+CSS+JavaScript在线美食订餐网站html模板源码30个页面:

    👨‍🎓静态网站的编写主要是用HTML DIV+CSS JS等来完成页面的排版设计👩‍🎓,常用的网页设计软件有Dreamweaver、EditPlus、HBuilderX、VScode 、Webstorm、Animate等等,用的最多的还是DW,当然不同软件写出的前端Html5代码都是一致的,本网页适合修改成为各种类型的产品展示网页,比

    2024年02月12日
    浏览(60)
  • 模板匹配Template Matching

     实现代码: 运行结果:

    2024年02月11日
    浏览(35)
  • [C++] 模板template

      目录 1、函数模板 1.1 函数模板概念 1.2 函数模板格式 1.3 函数模板的原理 1.4 函数模板的实例化 1.4.1 隐式实例化 1.4.2 显式实例化 1.5 模板参数的匹配原则 2、类模板 2.1 类模板的定义格式 2.2 类模板的实例化 讲模板之前呢,我们先来谈谈泛型编程: 泛型编程:编写与类型无关

    2024年02月13日
    浏览(58)
  • (二)模板templates

    Django模板层是为动态生成html服务的,非本文重点。前后端分离的设计更为常见,尽量少的涉及Django模板层内容。本文记录Django如何找到一个html文件。 在创建一个Django项目project后,目录下会生成一个同名目录和manage.py。创建一个app,并为app编写一个视图,如: 当通过路由访

    2024年01月16日
    浏览(23)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包