首页 > 后端开发 > Golang > 正文

如何将数据传递到 Go 的 `text/template` 包中的嵌套模板?

Mary-Kate Olsen
发布: 2024-10-26 08:32:30
原创
399 人浏览过

 How to Pass Data to Nested Templates in Go's `text/template` Package?

在 Go 模板之间传递数据

在 Go 的文本/模板包中,可以嵌套模板以重用常见的 HTML 元素。但是,如果您需要将额外的数据传递给一个。嵌套模板,默认模板机制不直接支持此功能。

要实现此目的,您可以创建一个自定义函数,将参数组合到切片中并返回它。将此函数注册到您的模板,然后使用它来传递参数。

这是一个示例:

package main

import (
    "text/template"
)

func main() {
    // Define the custom function to combine arguments
    func args(vs ...interface{}) []interface{} { return vs }

    // Parse the template with the custom function registered
    t, err := template.New("t").Funcs(template.FuncMap{"args": args}).Parse(...)
    if err != nil {
        // Handle error
    }

    // Render the template with the custom function
    t.ExecuteTemplate(..., template.Args(..., 5))

    // Access the arguments in the nested template
    {{ define "image_row" }}

       To stuff here {{index . 0}} {{index . 1}}

    {{ end }}
}
登录后复制

通过这种方法,您可以动态地将附加数据传递到嵌套模板,从而允许更灵活和可重用的 HTML 代码。

以上是如何将数据传递到 Go 的 `text/template` 包中的嵌套模板?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!