i am trying to place golang array( also slice,struct etc)to html so i can use array element in html Element content When returning html from golang gin web framework. Another problem is how to render these data with loop? such as flask jinjia works in this way.
{% block body %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
Usually you have a folder with template files so first you need to tell the gin where these templates are located:
router := gin.Default()
router.LoadHTMLGlob("templates/*")
Then in handler function you simply pass template name the data to HTML function like this:
func (s *Server) renderIndex(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", []string{"a", "b", "c"})
}
In index.tmpl
you can the loop the data like this:
{{range .}}
{{.}}
{{end}}
The .
is always the current context so in first line .
is the input data and inside the range loop .
is the current element.
Template example: https://play.golang.org/p/4_IPwD3Y84D
Documentation about templating: https://golang.org/pkg/text/template/
Great examples: https://astaxie.gitbooks.io/build-web-application-with-golang/en/07.4.html