
我想在 Go 模板中制作类似 UI 组件 100% 可重用的东西,但我不知道是否可以做到。所以我正在尝试做下一步:
{{define "components/menu-button"}}
{{.content}}
{{end}}
这是我的组件,它需要一个 map 因为属性是小写的。
然后在我的主页中,我有一个小菜单,它在我的导航栏中使用了 components/menu-button 组件的 3 倍:
{{template "components/menu-button" {"link": "/contact", "content": "Contact"}}} {{template "components/menu-button" {"link": "/docs", "content": "Docs"}}} {{template "components/menu-button" {"link": "/download", "content": "Download"}}}
但我不知道我是否可以以某种方式创建一个 map 就像我在示例中所做的那样,它就像 JSON 一样,但我尝试过。
顺便说一句,它给了我下一个错误:
unexpected "{" in template clause正确答案
Go 的模板不支持这种语法。
你可以做的是声明一个自定义函数,例如
func MakeMap(kvs ...any) map[any]any {
m := make(map[any]any)
for i := 0; i < len(kvs)-1; i+=2 {
m[kvs[i]] = kvs[i+1]
}
return m
}
然后您可以使用 使该函数可用于模板(*模板).Funcs,例如
t.Funcs(template.FuncMap{"M":MakeMap})
然后,在模板内,您可以使用密钥 M 调用该函数。
{{template "components/menu-button" (M "link" "/contact" "content" "Contact")}}










