首页  >  文章  >  后端开发  >  如何将数据作为参数传递给 Go 模板系统中包含的模板?

如何将数据作为参数传递给 Go 模板系统中包含的模板?

DDD
DDD原创
2024-10-28 04:29:30609浏览

How can I pass data as arguments to an included template in Go's templating system?

在模板之间传递数据

在 Go 的模板系统中,可能需要在多个模板之间传递数据,特别是当其中包含一个模板时其他。出现了问题,“如何将数据作为参数传递给包含的模板并在该模板中访问它?”

要实现此目的,您可以利用自定义函数将参数合并到单个切片值中。通过注册此函数,可以在模板调用中使用它。以下代码演示了如何完成此操作:

<code class="go">package main

import (
    "fmt"
    "html/template"
)

func main() {
    t, err := template.New("t").Funcs(template.FuncMap{
        "args": func(vs ...interface{}) []interface{} { return vs },
    }).Parse("{{ template \"image_row\" args . 5 }}")
    if err != nil {
        fmt.Println(err)
        return
    }

    err = t.Execute(template.Must(template.ParseFiles("index.html", "image_row.html")), nil)
    if err != nil {
        fmt.Println(err)
        return
    }
}

// index.html
{{ template "image_row" . | 5 }}

// image_row.html
{{ define "image_row" }}
   To stuff here {{index . 0}} {{index . 1}}
{{ end }}</code>

在 image_row 模板中,可以使用内置索引函数访问参数。例如,{{索引 . 0}} 将访问从 index.html 模板传递的第一个参数(索引 0),在本例中为数字 5。

此解决方案提供了一种在多个模板之间传递和访问数据的通用方法,支持自定义功能和高效的代码重用。

以上是如何将数据作为参数传递给 Go 模板系统中包含的模板?的详细内容。更多信息请关注PHP中文网其他相关文章!

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