
在 Go 模板中,with 和 range 语句会改变当前的作用域,也就是 . 所代表的值。 当需要在 with 或 range 内部访问外部作用域的变量时,可以使用 $ 符号。 $ 始终指向传递给 Execute 函数的初始数据,相当于根作用域,因此可以通过它来访问任何外部变量。正如摘要所说,$ 允许在任何嵌套作用域中访问根级别的数据。
使用 $ 访问外部作用域
以下示例演示了如何在 with 语句内部访问外部作用域的变量:
package main
import (
"os"
"text/template"
)
type Data struct {
OuterValue string
Inner InnerData
}
type InnerData struct {
InnerValue string
}
func main() {
tmpl, err := template.New("example").Parse(`
{{with .Inner}}
Outer: {{$.OuterValue}}
Inner: {{.InnerValue}}
{{end}}
`)
if err != nil {
panic(err)
}
data := Data{
OuterValue: "This is the outer value",
Inner: InnerData{
InnerValue: "This is the inner value",
},
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}在这个例子中,Data 结构体包含 OuterValue 和 Inner 字段。Inner 字段本身是一个 InnerData 结构体,包含 InnerValue 字段。
模板使用了 with .Inner 语句,这会将当前作用域设置为 data.Inner。 在 with 语句内部,可以使用 .InnerValue 访问内部值。 为了访问外部作用域的 OuterValue,我们使用了 $.OuterValue。 $ 指向传递给 Execute 函数的 data 变量,因此可以访问其任何字段。
运行该程序会输出:
Outer: This is the outer value Inner: This is the inner value
使用 range 访问外部作用域
同样,$ 也可以在 range 语句中使用。 假设我们有一个包含字符串切片的结构体:
ECSHOP仿QQ官方商城整站源码,基于ECSHOP V2.7.3制作。整体采用黑色。费用漂亮。适合综合,包包,首饰类商城网站使用。 安装方法:1.访问:域名/install,按照程序提示进行安装。2.登陆网站后台,然后进行数据还原。3.模板设置中,选择QQSHOW模板4.清空缓存。。。 注:还原数据后,网站后台信息:后台地址:admin后台用户名:admin后台密码:www.shopex5.co
package main
import (
"os"
"text/template"
)
type Data struct {
OuterValue string
Items []string
}
func main() {
tmpl, err := template.New("example").Parse(`
{{range $index, $item := .Items}}
Index: {{$index}}, Item: {{$item}}, Outer: {{$.OuterValue}}
{{end}}
`)
if err != nil {
panic(err)
}
data := Data{
OuterValue: "This is the outer value",
Items: []string{"Item 1", "Item 2", "Item 3"},
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}在这个例子中,range .Items 迭代 data.Items 切片。 在 range 循环内部,$index 和 $item 分别代表当前元素的索引和值。 为了访问外部作用域的 OuterValue,我们再次使用了 $.OuterValue。
运行该程序会输出:
Index: 0, Item: Item 1, Outer: This is the outer value Index: 1, Item: Item 2, Outer: This is the outer value Index: 2, Item: Item 3, Outer: This is the outer value
总结
$ 符号是 Go 模板中一个强大的工具,它允许在任何嵌套作用域中访问根级别的数据。 当使用 with 或 range 语句时,请记住使用 $ 来访问外部作用域的变量。 这使得模板能够灵活地访问和操作数据,从而创建动态和可定制的输出。
注意事项:
- $ 总是指向传递给 Execute 函数的原始数据,不会随着 with 或 range 的作用域改变而改变。
- 确保在模板中使用正确的字段名称来访问外部作用域的变量。
- 在复杂的模板结构中,合理使用 $ 可以提高代码的可读性和可维护性。









