3
votes

I am trying to place a 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 jinja works in this way.

{% block body %}
  <ul>
  {% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>
1

1 Answers

9
votes

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