Go语言多值替换的HTML模板实例分析
作者:pythoner 时间:2024-05-02 16:25:02
本文实例分析了Go语言多值替换的HTML模板用法。分享给大家供大家参考。具体如下:
这里通过两种方式提供基于HTML模板的多变量值替换。另外附加一个数组迭代的示例。
传入map实现多值替换
package main
import (
"html/template"
"os"
)
func main() {
t, _ := template.New("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args1 := map[string]string {"Username": "Hypermind", "MainPage": "http://hypermind.com.cn/go"}
_ = t.ExecuteTemplate(os.Stdout, "T", args1)
}
传入自定义结构实现多值替换
package main
import (
"html/template"
"os"
)
type Info struct{
Username string
MainPage string
}
func main() {
t, _ := template.New("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args2 := Info{Username: "Hypermind", MainPage: "http://hypermind.com.cn/go"}
_ = t.ExecuteTemplate(os.Stdout, "T", args2)
}
二维数组的迭代显示
package main
import (
"html/template"
"os"
)
type Matrix struct {
Array [9][9]int
}
func main() {
tmpl, _ := template.New("example").Parse(`
{{ $a := .Array }}
{{ range $a }}{{ $elem := . }}|{{ range $elem }}{{ printf "%d" . }}{{ end}}|
{{end}}`)
tmpl.Execute(os.Stdout, matrix)
}
希望本文所述对大家的Go语言程序设计有所帮助。
标签:Go语言,模板
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python之根据输入参数计算结果案例讲解
2022-08-27 07:44:50
![](https://img.aspxhome.com/file/2023/9/69499_0s.jpg)
pip安装python库的方法总结
2023-04-17 00:31:09
ThinkPHP3.0略缩图不能保存到子目录的解决方法
2024-04-30 08:47:06
浅谈Mybatis+mysql 存储Date类型的坑
2024-01-17 19:13:14
修正IE6不支持position:fixed的bug[译]
2009-08-01 12:44:00
python pip安装的包目录(site-packages目录的位置)
2022-08-23 13:20:38
在服务端合并和压缩JavaScript和CSS文件
2010-07-15 12:48:00
![](https://img.aspxhome.com/file/UploadPic/20107/15/cdn-and-minify-50s.png)
python利用faker库批量生成测试数据
2021-04-16 10:34:42
使用python实现飞机大战游戏
2021-05-11 12:02:16
![](https://img.aspxhome.com/file/2023/1/97111_0s.jpg)
Python通过yagmail实现发送邮件代码解析
2022-12-31 13:44:58
![](https://img.aspxhome.com/file/2023/4/125134_0s.png)
详解Go 依赖管理 go mod tidy
2024-05-02 16:25:17
![](https://img.aspxhome.com/file/2023/4/130714_0s.jpg)
Centos7安装和配置Mysql5.7
2024-01-21 12:02:22
![](https://img.aspxhome.com/file/2023/3/107913_0s.png)
Flask模板引擎Jinja2使用实例
2022-01-19 11:58:39
Python Numpy之linspace用法说明
2021-10-17 10:49:55
![](https://img.aspxhome.com/file/2023/3/113173_0s.png)
关于django连接mysql数据库并进行数据库的创建的问题
2024-01-22 04:50:12
![](https://img.aspxhome.com/file/2023/4/110334_0s.png)
asp函数InstrRev()介绍及获取文件名例子
2007-11-19 19:01:00
解决python3中自定义wsgi函数,make_server函数报错的问题
2023-06-13 08:03:24
Python中使用kitti数据集实现自动驾驶(绘制出所有物体的行驶轨迹)
2023-06-27 17:02:54
![](https://img.aspxhome.com/file/2023/8/89298_0s.png)
SQL语句练习实例之二——找出销售冠军
2024-01-26 01:12:19
在python中如何建立一个自己的包
2022-12-27 12:42:25
![](https://img.aspxhome.com/file/2023/5/72185_0s.png)