首頁 >後端開發 >Golang >如何在Go模板的Range Action中存取父/全域管道?

如何在Go模板的Range Action中存取父/全域管道?

Barbara Streisand
Barbara Streisand原創
2024-11-10 18:34:02252瀏覽

How to Access the Parent/Global Pipeline in Go Templates' Range Action?

在Go 模板的範圍操作中訪問父/全域管道

在Go 的文字/模板包中,能夠在範圍行動或父/全域管道至關重要。請考慮以下範例:

const page = `{{range .Files}}<script src="{{html .Path}}/js/{{html .}}"></script>{{end}}`

type scriptFiles struct {
    Path string
    Files []string
}

func main() {
    t := template.New("page")
    t = template.Must(t.Parse(page))

    t.Execute(os.Stdout, &scriptFiles{"/var/www", []string{"go.js", "lang.js"}})
}

在此範例中,在範圍操作內無法存取 .Path,因為 .dot 會轉換為目前的 Files 元素。

建議解決方案 - 使用 $ 變數

根據text/template包文檔,$變數保存傳遞給的資料參數執行,這是.dot的初始值。因此,要在範圍操作中使用$.Path 存取外部作用域的路徑,請使用以下變體:

const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`

替代解決方案- 自訂變數

之前範圍操作,可以定義自訂變數以將值傳遞到範圍範圍。例如:

const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`

以上是如何在Go模板的Range Action中存取父/全域管道?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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