搜尋
首頁後端開發Golang如何將多個值從 Go 範本傳遞到嵌套範本?

How can I pass multiple values from a Go template to a nested template?

將多個值從模板傳遞到模板

在 Go 模板中,可以使用 {{模板}} 操作。但是,此操作僅接受單一資料值作為輸入。當需要將多個資料實體傳遞給嵌套範本時,需要一個解決方案。

用於資料打包的自訂函數

Go 的範本系統允許使用以下方式註冊自訂函數Template.Funcs() 方法。這些函數可以在資料傳遞到模板之前對資料進行操作,從而實現資料操作和打包。

在需要將多個值傳遞給模板的情況下,可以建立一個自訂函數來包裝將這些值放入單一實體中,例如映射或結構。然後可以將此包裝的實體傳遞給 {{template}} 操作。

範本修改

定義自訂函數後,可以修改範本以呼叫此函數並將包裝的資料實體傳遞給巢狀範本。其語法為:

{{template "templateName" (customFunctionName data1 data2)}}

範例

考慮以下城市和地區結構:

type City struct {
    ID      int
    Name    string
    Regions []Region
}  

type Region struct {
    ID               int
    Name             string
    Shops            []Destination
    Masters          []Master
    EducationCenters []Destination
}

傳遞多個資料實體對於嵌套模板,自訂函數Wrap()可以定義為如下:

func Wrap(shops []Destination, cityName, regionName string) map[string]interface{} {
    return map[string]interface{}{
        "Shops":      shops,
        "CityName":   cityName,
        "RegionName": regionName,
    }
}

此函數將商店陣列以及城市和地區名稱包裝到地圖中。修改後的範本現在如下所示:

const src = `
{{define "data"}}
    City: {{.CityName}}, Region: {{.RegionName}}, Shops: {{.Shops}}
{{end}}
{{- range . -}}
        {{$city:=.Name}}
        {{- range .Regions -}}
              {{$region:=.Name}}
              {{- template "data" (Wrap .Shops $city $region) -}}
        {{end}}
{{- end}}`

可運行範例

以下程式碼示範如何在實作中使用此解決方案:

package main

import (
    "os"
    "text/template"
)

type City struct {
    ID      int
    Name    string
    Regions []Region
}  

type Region struct {
    ID               int
    Name             string
    Shops            []Destination
    Masters          []Master
    EducationCenters []Destination
}

type Destination struct {
    Name string
}

func main() {
    t := template.Must(template.New("cities.gohtml").Funcs(template.FuncMap{
        "Wrap": Wrap,
    }).Parse(src))
    CityWithSomeData := []City{
        {
            Name: "CityA",
            Regions: []Region{
                {Name: "CA-RA", Shops: []Destination{{"CA-RA-SA"}, {"CA-RA-SB"}}},
                {Name: "CA-RB", Shops: []Destination{{"CA-RB-SA"}, {"CA-RB-SB"}}},
            },
        },
        {
            Name: "CityB",
            Regions: []Region{
                {Name: "CB-RA", Shops: []Destination{{"CB-RA-SA"}, {"CB-RA-SB"}}},
                {Name: "CB-RB", Shops: []Destination{{"CB-RB-SA"}, {"CB-RB-SB"}}},
            },
        },
    }
    if err := t.ExecuteTemplate(os.Stdout, "cities.gohtml", CityWithSomeData); err != nil {
        panic(err)
    }
}

const src = `
{{define "data"}}
    City: {{.CityName}}, Region: {{.RegionName}}, Shops: {{.Shops}}
{{end}}
{{- range . -}}
        {{$city:=.Name}}
        {{- range .Regions -}}
              {{$region:=.Name}}
              {{- template "data" (Wrap .Shops $city $region) -}}
        {{end}}
{{- end}}`

此程式碼示範如何使用自訂函數將多個資料實體成功傳遞到巢狀範本。

以上是如何將多個值從 Go 範本傳遞到嵌套範本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
測試代碼依賴於INET功能的代碼測試代碼依賴於INET功能的代碼May 03, 2025 am 12:20 AM

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

將GO的錯誤處理方法與其他語言進行比較將GO的錯誤處理方法與其他語言進行比較May 03, 2025 am 12:20 AM

go'serrorhandlingurturnserrorsasvalues,與Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

設計有效界面的最佳實踐設計有效界面的最佳實踐May 03, 2025 am 12:18 AM

AnefactiveInterfaceingoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForabStractionToswaPimplementations withoutchangingCallingCode.3)

集中式錯誤處理策略集中式錯誤處理策略May 03, 2025 am 12:17 AM

集中式錯誤處理在Go語言中可以提升代碼的可讀性和可維護性。其實現方式和優勢包括:1.將錯誤處理邏輯從業務邏輯中分離,簡化代碼。 2.通過集中處理錯誤,確保錯誤處理的一致性。 3.使用defer和recover來捕獲和處理panic,增強程序健壯性。

init in Init函數的替代方案,用於go中的包裝初始化init in Init函數的替代方案,用於go中的包裝初始化May 03, 2025 am 12:17 AM

Ingo,替代詞InivestoIniTfunctionsIncludeCustomInitializationfunctionsandsingletons.1)customInitializationfunctions hownerexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssetupssetupssetups.2)單次固定無元素限制ininconconcurrent

與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境