首頁  >  文章  >  後端開發  >  如何將資料傳遞到 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