ホームページ  >  記事  >  バックエンド開発  >  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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。