3

I'm trying to display the output in HTML templates instead of JSON. Somehow it is not working as expected. I tried in different ways, but no luck. Any help would be great. Here is my code

c.HTML(
    http.StatusOK,
    "templates/index.html",
    gin.H{
        "status": http.StatusOK,
        "data": _books,
    },
)
David Buck
  • 3,752
  • 35
  • 31
  • 35
deepu
  • 107
  • 3
  • 10

1 Answers1

2

After looking at the screenshot I noticed that there is no call to r.LoadHTMLFiles("templates/index.html") or router.LoadHTMLGlob("templates/*"). If this is not done in any of your other files, then that might be the problem.

Here is a small example app that I created for rendering HTML templates that you can hopefully use to get your app working:

main.go

package main

import (
    "log"
    "net/http"

    "github.com/gin-gonic/gin"
)

// Book ...
type Book struct {
    Title  string
    Author string
}

func main() {
    r := gin.Default()
    r.LoadHTMLFiles("index.html")

    books := make([]Book, 0)
    books = append(books, Book{
        Title:  "Title 1",
        Author: "Author 1",
    })
    books = append(books, Book{
        Title:  "Title 2",
        Author: "Author 2",
    })

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "books": books,
        })
    })
    log.Fatal(r.Run())
}

index.html

<html>
    {{ range $book := .books }}
    <h1>{{ .Title }}</h1>
    <h3>{{ .Author }}</h3>
    <hr/>
    {{ end }}
</html>
michaeljdennis
  • 602
  • 1
  • 7
  • 12