首页  >  文章  >  后端开发  >  如何在Go模板中传入“途中创建”的地图

如何在Go模板中传入“途中创建”的地图

WBOY
WBOY转载
2024-02-05 23:39:03575浏览

如何在Go模板中传入“途中创建”的地图

问题内容

我想在 Go 模板中制作类似 UI 组件 100% 可重用的东西,但我不知道是否可以做到。所以我正在尝试做下一步:

<code>{{define "components/menu-button"}}
<a href="{{.link}}" class="text-white">{{.content}}</a>
{{end}}
</code>

这是我的组件,它需要一个 map 因为属性是小写的。

然后在我的主页中,我有一个小菜单,它在我的导航栏中使用了 components/menu-button 组件的 3 倍:

<code><div class="hidden gap-4 sm:flex">
    {{template "components/menu-button" {"link": "/contact", "content": "Contact"}}}
    {{template "components/menu-button" {"link": "/docs", "content": "Docs"}}}
    {{template "components/menu-button" {"link": "/download", "content": "Download"}}}
</div>
</code>

但我不知道我是否可以以某种方式创建一个 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")}}

https://www.php.cn/link/0740bb92e583cd2b88ec7c59f985cb41

以上是如何在Go模板中传入“途中创建”的地图的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除