unrolled / render

Go package for easily rendering JSON, XML, binary data, and HTML templates responses.
MIT License
1.94k stars 146 forks source link

Asset and AssetNames render.Options fields #67

Closed errashe closed 6 years ago

errashe commented 6 years ago
package main

import . "fmt"
import "io"

import "github.com/labstack/echo"
import "github.com/gobuffalo/packr"
import "github.com/unrolled/render"

var box packr.Box

type RenderWrapper struct { // We need to wrap the renderer because we need a different signature for echo.
    rnd *render.Render
}

func NewRender(ro render.Options) *RenderWrapper {
    return &RenderWrapper{render.New(ro)}
}

func (r *RenderWrapper) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return r.rnd.HTML(w, 0, name, data) // The zero status code is overwritten by echo.
}

var ro render.Options = render.Options{
    Asset: func(name string) ([]byte, error) {
        Println("A")
        return box.MustBytes(Sprintf("%s.tmpl", name))
    },
    AssetNames: func() []string {
        return box.List()
    },
}

func main() {
    box = packr.NewBox("./html")
    r := NewRender(ro)
    e := echo.New()

    e.Renderer = r

    e.GET("/", func(c echo.Context) error {
        return c.Render(200, "main", nil)
    })

    Println(e.Start(":1323"))
}

Won't work: html/template: "main" is undefined. But box.MustBytes("main.tmpl") returns bytes from file. No additional docs found (or i can't). What i doing wrong?

errashe commented 6 years ago

Actually, i found solution. In function, which one should check existing those templates there is a mistake: empty Templates directory fills with templates string. And when parsing templates - just skiping them all, cuz they don't have substring with this templates string. So, i need to add substring to my AssetNames function to make sure, what everything works properly.

AssetNames: func() []string {
    var ret []string
    for _, el := range box.List() {
        ret = append(ret, Sprintf("/%s", el))
    }
    return ret
},
Directory:  "/",

And everything works as expected.