I am using Gin gonic for my Go project, and in my footer.tmpl, I will have more than 10++ navigation links, rather than write 'link' multiple times, it would be much easier if I create an array containing the links, and title and loop through it, right?
The problem is as I have researched, Golang does not have an inbuilt function to declare an array/map variables inside view files (.tmpl/.html).
Why do I need the array to be inside the view file is because this footer.tmpl will be included in almost all other pages, if I have to write the array inside the controller and passed the variable, it will be too troublesome to pass the array params to all the pages.
This is my Golang code:
r.GET("/", func(c *gin.Context) {
tmpl := template.Must(template.ParseFiles("templates/layout.tmpl", "templates/index.tmpl", "templates/common/header_a.tmpl", "templates/common/footer_a.tmpl"))
r.SetHTMLTemplate(tmpl)
var hometabList = []HomeTab{
HomeTab{Title: "Tab1", Value: 1},
HomeTab{Title: "Tab2", Value: 2},
HomeTab{Title: "Tab3", Value: 3},
}
c.HTML(200, "layout", gin.H {
"tab": hometabList,
"product": "123",
})
})
I am a PHP developer moving to Go, in PHP you can do this inside the view:
view.php
<body>
<?php
$arr_link = ['link1', 'link2', 'link3'];
for($i = 0; $i < count($arr_link); $i++): ?>
<div><a><?= $arr_link[$i]; ?></a></div>
<?php endfor; ?>
</body>
By doing this, when I include this footer inside another page, it will be easier to maintain the codes.