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.

0

1 Answer 1

1

You can use range in your template:

{{range .YourListItems}}
  <div><a href="{{.Url}}">{{.Name}}</a></div>
{{end}}
Sign up to request clarification or add additional context in comments.

3 Comments

You could find more at here golang.org/pkg/html/template
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 there is a working example about how to implement range here: stackoverflow.com/a/21303045/1035977

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.