Rendering HTML templates
In this section, you will add the functionality to display a list of recipes dynamically by generating an index.html
file from the server side. The Gin framework uses the Go standard text/template
and html/template
packages in the background to generate text and HTML outputs.
To get started, proceed as follows:
- Create a
Recipe
struct. The structure will hold just two fields: a name and picture. This can be represented as follows:type Recipe struct {    Name    string `json:"name"`    Picture string `json:"picture"` }
- Next, update the
IndexHandler
handler to create arecipes
slice. Then, call thec.HTML
method to render theindex.tmpl
file by passing therecipes
slice. To keep things simple, the list of recipes is kept in memory, which is why we will initialize therecipes
slice with two hardcoded recipes, as follows:func IndexHandler(c *gin.Context) { Â Â Â recipes...