我有下面的JSON結構。beego模板 - 使用鍵值或地圖值作爲其他地圖的關鍵字或將其傳遞給模板函數
func getJsonMappings() *string {
data := `{
"CategoryGroup": {
"Category subgrp1": ["type1", "type2"],
},
"CategoryGroupDetail" : {
"type1":{
"extension":"abc",
"title" : "this is description",
"other": "i have some other details apart from above in this map"
},
"type2" :{
"extension":"abc",
"title" : "this is description",
"other": "i have some other details apart from above in this map"
}
}
}`
return &data
}
我解組上面JSON的控制器功能定義
func (this *MainPageController) Get() {
jsonData := getJsonMappings()
var catMapObj map[string]interface{}
err := json.Unmarshal([]byte(*jsonData), &catMapObj)
if err != nil {
panic(err.Error())
}
this.Data["CategoryGroup"] = catMapObj["CategoryGroup"]
this.Data["CatAttributeMapping"] = catMapObj["CatAttributeMapping"]
this.TplName = "index.tpl"
}
,並試圖使下面的模板golang數據結構如下圖所示。
<ul class="collapsible collapsible-accordion">
{{ range $eachCategory, $subCategoriesList := .CategoryGroup }}
<li class="bold"><a class="collapsible-header waves-effect waves-teal">{{ $eachCategory }}</a>
<div class="collapsible-body" style="">
<ul>
{{ range $_, $subConvertorCategoryId := $subCategoriesList }}
<li><a id="{{ $subConvertorCategoryId }}" class='doc_cvt' href="#">{{ $subConvertorCategoryId|getCategoryTitle }}</a></li>
{{ end }}
</ul>
</div>
</li>
{{ end }}
</ul>
其中getCategoryTitle是模板函數。但是我沒有得到任何值作爲函數參數的類型變量。我的模板函數定義看起來像
func GetCategoryTitle(type string) (title string) {
.....
}
,如果我硬編碼「類型」的值設置爲「TYPE1」裏面的功能則一切正常。但我想在運行時從模板發送值。在同一時刻,我可以將「.CategoryGroup」的值傳遞給模板函數。
因此,我的問題是:
1如何通過鑰匙或在分析模板golang模板函數接收到的地圖的價值?
2-如果你會仔細看上面的結構,那麼你會發現我不需要寫模板函數。我應該得到像 {{.CategoryGroupDetail。$ subConvertorCategoryId.title}}的值。但我無法這樣做。我用django(python框架)做了同樣的事情。 golang/beego也一定有辦法做到這一點。
我是golang和Beego的新手。請指導我如何繼續下去。
Try1:
<ul class="collapsible collapsible-accordion">
{{ range $eachCategory, $subCategoriesList := .CategoryGroup }}
<li class="bold"><a class="collapsible-header waves-effect waves-teal">{{ $eachCategory }}</a>
<div class="collapsible-body" style="">
<ul>
{{ range $_, $subConvertorCategoryId := $subCategoriesList }}
{{ $categoryDetail := index .CatAttributeMapping $subConvertorCategoryId}}
<li><a id="{{ $subConvertorCategoryId }}" class='doc_cvt' href="#">{{ $categoryDetail.title }}</a></li>
{{ end }}
</ul>
</div>
</li>
{{ end }}
我得到下面的錯誤在運行時 -
template: index.tpl:38:32: executing "index.tpl" at <.CatAttributeMapping>: can't evaluate field CatAttributeMapping in type interface {}
@ Diablojoe-感謝您的回覆。但結構有點不同於你所設想的。請再次參考json結構。 – virus
@ Diablojoe-我在你的指導下添加了Try1作爲新的嘗試。請看看它。看起來我應該在將jsone數據轉換爲golang結構的同時使用struct而不是interface {}。 – virus
@ Diablojoe-沒問題..我已經嘗試過結構已經..那個時候以及我得到了錯誤。順便說一下,只要你有時間,請拿出解決方案。這將有所幫助。 – virus