josephspurrier / gowebapp

Basic MVC Web Application in Go
MIT License
1.14k stars 197 forks source link

Embed Files in Go 1.16 #51

Closed karfianto closed 3 years ago

karfianto commented 3 years ago

How to embed template and static folder using this app's templating system and view?

Many thanks

josephspurrier commented 3 years ago

You should add this to a Go file in the template folder to allow including templates during build time:

//go:embed */*.tmpl
var Assets embed.FS

You'll then have to update vendor/app/shared/view/view.go so it loads the assets like this instead of using ParseFiles.

// Parse the template.
tmpl, err := template.New(path.Base(templatePath)).Funcs(fm).ParseFS(Assets, templatePath)
if err != nil {
    return "", err
}

// Execute the template.
err = tmpl.Execute(buf, data)
if err != nil {
    return "", err
}
karfianto commented 3 years ago

Here's my try

template/embed.go

package template

import "embed"

//go:embed */*.tmpl

var Assets embed.FS

app\shared\view\view.go

import (
...
    "path/filepath"
    tmpl "github.com/josephspurrier/gowebapp/template"
)
...
    //templates, err := template.New(v.Name).Funcs(pc).ParseFiles(templateList...)
    templates, err := template.New(filepath.Base(v.Name+".tmpl")).Funcs(pc).ParseFS(tmpl.Assets, "*/*.tmpl")

...
    //err := tc.Funcs(pc).ExecuteTemplate(w, rootTemplate+"."+v.Extension, v.Vars)
    err := tc.Execute(w, v.Vars)

Compiling was successful but the web is now blank (nothing shown)

josephspurrier commented 3 years ago

You need to update the embedded comment to: //go:embed *.tmpl */*.tmpl. You need to go back to using the templateList... and then you need to update the templateLIst for loop to just append the extensions instead of the full path.

I've got a branch working with embedded templates: https://github.com/josephspurrier/gowebapp/commit/3603a3b1db0e26ea61c84448f234342b2a241f52

karfianto commented 3 years ago

Thanks @josephspurrier

It works well with branch https://github.com/josephspurrier/gowebapp/tree/embedded-templates

Love it!