
go template 如何赋值变量?
go 中通过变量赋值来填充模板内容,这与 php 的 assign 方法类似。
当执行模板时,通过 execute 函数的第二个参数传入变量。该参数可以是 map 或 struct,包含模板中使用的变量。
对于您的示例代码,可以如下方式赋值变量:
import (
"text/template"
"os"
)
type filename struct {
name string
}
func main() {
// 模板内容
const templatetext = `
<ul>
{{range .filelist}}
<li>{{.name}}</li>
{{end}}
</ul>
`
// 数据
filelist := []filename{{"a.txt"}, {"b.txt"}}
// 创建模板
t := template.must(template.new("tmpl").parse(templatetext))
// 赋值并执行模板
err := t.execute(os.stdout, map[string]interface{}{"filelist": filelist})
if err != nil {
panic(err)
}
}结果如下:
<ul> <li>a.txt</li> <li>b.txt</li> </ul>
以上就是Go template 如何赋值变量?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号