skip to Main Content

On my Ubuntu 22.10 digitalocean server, I’m experimenting with Golang and Fiber and the html template engine. Loving it so far.

It all works, including the Mysql connection and sending email. Except for one thing.

I keep getting the error render: template index does not exist.

File system:

├── /gogo
   ├── main
   ├── main.go
   ├── go.mod
   ├── go.sum
   ├── /views
        └── index.html
   └── /public
        └── plaatje.png

The code of my main.go:

package main

import (
    "fmt"
    "log"
    fiber "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/html"
)

func main() {
    // Initialize standard Go html template engine
    template_engine := html.New(
        "./views",
        ".html",
    )

    // start fiber
    app := fiber.New(fiber.Config{
        Views: template_engine,
    })

    // add static folder
    app.Static(
        "/static",  // mount address
        "./public", // path to the file folder
    )

    // endpoint
    app.Get("/", func(c *fiber.Ctx) error {
        // Render index template
        return c.Render("index", fiber.Map{
            "Title": "It works",
            "Plat":  "almost",
        })
    })

    log.Fatal(app.Listen(":9990"))
}

The index.html file:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=Unicode">
    <title>{{.Title}}</title>
</head>
<body>
    <h1>{{.Title}}</h1>
    <p>{{.Plat}}</p>
    <p><img src="./static/plaatje.png"></p>
</body>
</html>

When I run it locally on my Mac, it all works and the template is rendered as it should.

But on the Ubuntu server it all works except for the template, with the given error:

render: template index does not exist

I’ve tried changing ownership and permissions in Ubuntu: no results. However this is a bit of a blind spot for me, so this might still be the isue…

I’ve tried tinkering with the views path (./views, /views, views. etc): no results.

I’ve tried return c.Render("index.html", fiber.Map{: no results.

What am I missing?

2

Answers


  1. Chosen as BEST ANSWER

    The experiment with go run . gave a clue. When running it as a service, the mount point is not the dir where main is, but a path elsewhere on the server.

    Changing...

        template_engine := html.New(
            "./views",
            ".html",
        )
    

    ... with a relative path to an absolute path ...

        template_engine := html.New(
            "/home/username/go/views",
            ".html",
        )
    

    ... solved the issue.

    This issue is not mentioned in any source on this topic.


  2. Look for an error, it will come out above the box of Fiber info. For me it was this: 2023/03/12 15:40:58 [Warning]: failed to load views: template: apply:9: function "t" not defined. If your templates compile, they will be found using the relative path.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search