gofiber/template

mustache: partials not working with embedded filesystems

zachmann opened this issue · 4 comments

When using an embedded http.Filesystem partials don't use that filesystem, i.e. the partials are not included.

This is due to the following call:

tmpl, err := mustache.ParseString(string(buf))
//mustache.ParseStringPartials()

The mustache.ParseString method eventually calls
https://github.com/cbroglie/mustache/blob/2ebfd282f6d111da6e36db2ca3995abcab30dfb7/mustache.go#L717-L724
which uses the real filesystem to find partials.

I submitted PR #104 to fix this issue. The PR introduces a new function NewFileSystemPartials which takes a Filesystem specially for partials (of course a user instead can also use the same Filesystem already used for the other template files). If the partialFileSystem is set the above call to mustache.ParseString is replaced with a call to mustache.ParseStringPartials that uses the embedded Filesystem for the partials.

Feel free to adapt the PR.

hi i tried it myself, with partials in the embedded filesystem and it seems to work, without any adjustments

package main

import (
    "embed"
    "log"
    "net/http"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/mustache"
)

//go:embed views/*
var viewsfs embed.FS

func main() {

    engine := mustache.NewFileSystem(
        http.FS(viewsfs),
        ".mustache",
    )

    // Pass the engine to the Views
    app := fiber.New(fiber.Config{
        Views: engine,
    })


    app.Get("/", func(c *fiber.Ctx) error {
        // Render index
        return c.Render("views/index", fiber.Map{
             "Title": "Hello, World!",
        })
    })

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

views folder from here:
https://github.com/gofiber/template/tree/master/mustache/views

Output:
image

It only works if / because the files are (also) available on the real filesystem on the correct (expected) paths. If you run the binary from a different location, the paths are not as expected anymore and it will not find the partials, which results in only rendering the Hello, World!.

I'll update the PR with the requested changes.

ok, thx