请问 go template 具体是如何赋值变量到模板的?
时间:2023-01-08
浏览:441
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《请问 go template 具体是如何赋值变量到模板的?》,聊聊go,我们一起来看看吧!
问题内容
小弟是做 php 开发出身的,最近在学 go,因需求需要用到 go template 方面的东西,看了网上很多关于 template 用法方面的文章,感觉写的都很难懂,讲的都是写云里雾里不切实际的东西,我就以 php 的做法请教一下各位大神吧:
php 赋值给模板的操作,一般都是通过 assign 方法,两个参数,一个是 php 文件中的变量名称,一个是 模板中的变量名称,简洁易懂,请问 go 是如何实现这个步骤的呢?
比如我现在代码如下:
fileList := GetFileList(file.Name) //这是个切片类型
t1, err := template.ParseFiles("html/show_dir_list.html")
if err != nil {
panic(err)
}
_ = t1.Execute(w, fileList)我该如何将 fileList 这个变量的内容赋值到模板中去呢?
目前模板代码如下:
{{range $i, $v := .fileList}}
{{$v.Name}}{{end}}
正确答案
package main
import (
"os"
"text/template"
)
type FileName struct {
Name string
}
func main() {
// Define a template.
const templateText = `
{{range $i, $v := .fileList}}
{{$v.Name}}
{{end}}
`
// Prepare some data to insert into the template.
fileList := []FileName{{"a.txt"}, {"b.txt"}}
// Create a new template and parse the letter into it.
t := template.Must(template.New("tmpl").Parse(templateText))
// Execute the template for each recipient.
err := t.Execute(os.Stdout, map[string]interface{}{"fileList": fileList})
if err != nil {
panic(err)
}
}结果是
a.txtb.txt
变量传进模板靠
Execute的第二个参数,你可以用
map或者
struct来传。直接传
fileList也可以,注意Go模板里的
.代表的就是你传的这个参数。
直接传
fileList的写法是这样。
// Define a template.
const templateText = `
{{range $i, $v := .}}
{{$v.Name}}
{{end}}
`
// Prepare some data to insert into the template.
fileList := []FileName{{"a.txt"}, {"b.txt"}}
// Create a new template and parse the letter into it.
t := template.Must(template.New("tmpl").Parse(templateText))
// Execute the template for each recipient.
err := t.Execute(os.Stdout, fileList)
if err != nil {
panic(err)
}本篇关于《请问 go template 具体是如何赋值变量到模板的?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.29
11.29
11.29
11.29
热门专题
