
在模板之間傳遞數據
在Go 的模板系統中,可能需要在多個模板之間傳遞數據,特別是當其中包含一個模板時其他。出現了問題,「如何將資料作為參數傳遞給包含的範本並在該範本中存取它?」
要實現此目的,您可以利用自訂函數將參數合併到單一切片值中。透過註冊此函數,可以在模板呼叫中使用它。以下程式碼示範如何完成此操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <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
}
}
{{ template "image_row" . | 5 }}
{{ define "image_row" }}
To stuff here {{index . 0}} {{index . 1}}
{{ end }}</code>
|
登入後複製
在 image_row 範本中,可以使用內建索引函數存取參數。例如,{{索引 . 0}} 將存取從 index.html 範本傳遞的第一個參數(索引 0),在本例中為數字 5。
此解決方案提供了一種在多個範本之間傳遞和存取資料的通用方法,支援自訂功能和高效的程式碼重用。
以上是如何將資料作為參數傳遞給 Go 範本系統中包含的範本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!