首页  >  文章  >  后端开发  >  如何将数据传递到 Go 的 `text/template` 包中的嵌套模板?

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

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-26 08:32:30383浏览

 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn