首頁  >  文章  >  後端開發  >  如何在 Go 的 text/template 套件中的模板之間傳遞資料?

如何在 Go 的 text/template 套件中的模板之間傳遞資料?

DDD
DDD原創
2024-10-27 02:59:03619瀏覽

How to Pass Data Between Templates in Go's text/template Package?

在模板之間傳遞資料

模板渲染中的一個常見要求是能夠在模板之間傳遞資料。在 Go 的文字/模板包中,這可以使用函數和模板呼叫技術的組合來實現。

要將簡單的數字作為附加參數傳遞給巢狀模板,您可以定義一個合併其參數的函數轉換為單一切片值。然後可以在模板呼叫中註冊並使用該函數。

這裡有一個範例:

<code class="go">func args(vs ...interface{}) []interface{} {
    return vs
}</code>
<code class="go">t, err := template.New("t").Funcs(template.FuncMap{"args": args}).Parse(...)</code>

在index.html範本中,使用args函式合併目前有附加參數的資料:

<code class="html">{{ template "image_row" args . 5 }}</code>

在image_row.html 範本中,使用索引內建函數存取參數:

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

這種方法可讓您傳遞任意資料在範本之間建立更複雜且可重複使用的範本元件。

以上是如何在 Go 的 text/template 套件中的模板之間傳遞資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn