Created
May 30, 2020 04:27
-
-
Save SnowyPainter/c4e470aacde1cd09fea380df470c969e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"html/template" | |
"io" | |
"io/ioutil" | |
"github.com/labstack/echo" | |
) | |
//ErrLastCharactorOfDirectoryPathMustBeSlash ErrLastCharactorOfDirectoryPathMustBeSlash | |
var ErrLastCharactorOfDirectoryPathMustBeSlash error = errors.New("Last Charactor Of Directory Path Must Be Slash") | |
//Template template | |
type Template struct { | |
templates map[string]*template.Template | |
} | |
//NewTemplate creates new template of html | |
func NewTemplate() *Template { | |
return &Template{ | |
templates: make(map[string]*template.Template), | |
} | |
} | |
//Render rendered | |
func (t *Template) Render(w io.Writer, htmlName string, data interface{}, c echo.Context) error { | |
if tmpl, exist := t.templates[htmlName]; exist { | |
return tmpl.ExecuteTemplate(w, "page", data) | |
} | |
return errors.New("There is no " + htmlName + " in Template map.") | |
} | |
//AddFilesInDirectory adds all of files in directoryPath to called template object. | |
func (t *Template) AddFilesInDirectory(directoryPath string, nav string, footer string) error { | |
if string(directoryPath[len(directoryPath)-1]) != "/" { | |
return ErrLastCharactorOfDirectoryPathMustBeSlash | |
} | |
files, err := ioutil.ReadDir(directoryPath) | |
if err != nil { | |
return err | |
} | |
for _, file := range files { | |
if file.IsDir() { | |
continue | |
} | |
name := file.Name() | |
t.templates[name] = template.Must(template.ParseFiles(nav, footer, directoryPath+name)) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment