Search code examples
gogoland

Issue while tying to pass array of class objects into html


Issue details

When I try to write following line in html, it says:

category_id is an unexported field of struct type Categories.Category

<option value="eded">{{ $element.category_id }}</option>

but when I try this <option value="eded">{{ $element }}</option> I get following results. therefore I can confirm data is being transferred successfully in html

enter image description here

Category Handler code

type PageProps struct {
    Categories []Category
}

type Category struct {
    category_id int
}

type CategorydHandler struct {
    PageData PageProps
}

func Instantiate(pageProps PageProps) *CategorydHandler {
    return &CategorydHandler{
        PageData: pageProps,
    }
}

func (pageData *CategorydHandler) GetCategories() []Category {
    query := "select * from tblcategory order by category_id"
    result, err := db.Query(query)
    for result.Next() {
        var objCategory Category
        result.Scan(&objCategory.category_id)
        pageData.PageData.Categories = append(pageData.PageData.Categories, objCategory)
    }
    return pageData.PageData.Categories
}

main.go

categories := objCategories.GetCategories()

html code

<select multiple type="text">
    {{ range $index, $element := .Categories }}
        <option value="eded">{{ $element }}</option>
    {{ end }}        
</select>

Solution

  • Data is there, but you cannot access it by name, because it is not exported.

    Export the field-

    type Category struct {
        Category_id int  // Capitalize the field name to export it
    }