mark2web/helper/render.go

68 lines
1.7 KiB
Go
Raw Normal View History

2019-02-27 17:33:26 +01:00
package helper
import (
"log"
"path"
"regexp"
"strings"
"gitbase.de/apairon/mark2web/config"
"github.com/flosch/pongo2"
)
var templateCache = make(map[string]*pongo2.Template)
var currentContext map[string]interface{}
var templateDir string
func BackToRoot(curNavPath string) string {
tmpPath := ""
if curNavPath != "" {
for i := strings.Count(curNavPath, "/") + 1; i > 0; i-- {
tmpPath += "../"
}
}
return tmpPath
}
// SetTemplateDir sets base directory for searching template files
func SetTemplateDir(dir string) {
templateDir = dir
}
// RenderTemplate renders a pongo2 template with context
func RenderTemplate(filename string, ctx map[string]interface{}) (string, error) {
currentContext = ctx
templateFile := templateDir + "/" + filename
template := templateCache[templateFile]
if template == nil {
var err error
if template, err = pongo2.FromFile(templateFile); err != nil {
log.Panicf("could not parse template '%s': %s", templateFile, err)
} else {
templateCache[templateFile] = template
}
}
return template.Execute(ctx)
}
func FixAssetsPath(str, curNavPath string) string {
if find := config.Config.Assets.FixTemplate.Find; find != "" {
Log.Debugf("fixing assets paths for path '%s'", curNavPath)
repl := config.Config.Assets.FixTemplate.Replace
toPath := config.Config.Assets.ToPath
bToRoot := BackToRoot(curNavPath)
regex, err := regexp.Compile(find)
if err != nil {
log.Panicf("could not compile regexp '%s' for assets path: %s", find, err)
}
repl = bToRoot + toPath + "/" + repl
repl = path.Clean(repl) + "/"
Log.Debugf("new assets paths: %s", repl)
return regex.ReplaceAllString(str, repl)
} else {
return str
}
}