1

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.

Flimzy
  • 60,850
  • 13
  • 104
  • 147
Charas
  • 1,509
  • 4
  • 16
  • 42
  • 1
    You can [declare a function](https://stackoverflow.com/questions/35550326/golang-templates-and-passing-funcs-to-template) and call it from your template. Or you can use [nested templates](https://stackoverflow.com/questions/11467731/is-it-possible-to-have-nested-templates-in-go-using-the-standard-library-googl) – blackgreen Jun 14 '20 at 10:40

1 Answers1

1

You can use range in your template:

{{range .YourListItems}}
  <div><a href="{{.Url}">{{.Name}}</a></div>
{{end}}
Cem Ikta
  • 1,112
  • 9
  • 11
  • You could find more at here https://golang.org/pkg/html/template/ – Misti Jun 14 '20 at 23:20
  • 1
    Thanks for your answer, but the question is how to I instantiate .YourListItems in the template view? because if not then I have to manually pass the .YourListItems to all my templates one by one, which is troublesome when I have let's say 30-40 templates. While if I could make the variable in the template itself, I just need to write it once in the template – Charas Jun 15 '20 at 09:29
  • @Charas there is a working example about how to implement `range` here: https://stackoverflow.com/a/21303045/1035977 – Gwyneth Llewelyn Aug 12 '20 at 10:25