package mark2web import ( "log" "path" "regexp" "gitbase.de/apairon/mark2web/config" "gitbase.de/apairon/mark2web/context" "gitbase.de/apairon/mark2web/helper" "github.com/flosch/pongo2" ) var templateCache = make(map[string]*pongo2.Template) var templateDir string // 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, treeNodeConfig *config.PathConfigTree, pathConfig *config.PathConfig, ctx *pongo2.Context) (string, error) { context.CurrentContext = ctx context.CurrentTreeNodeConfig = treeNodeConfig context.CurrentPathConfig = pathConfig 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) } // FixAssetsPath replaces assets path based on current path func FixAssetsPath(str, curNavPath string) string { if find := config.Config.Assets.FixTemplate.Find; find != "" { helper.Log.Debugf("fixing assets paths for path '%s'", curNavPath) repl := config.Config.Assets.FixTemplate.Replace toPath := config.Config.Assets.ToPath bToRoot := helper.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) + "/" helper.Log.Debugf("new assets paths: %s", repl) return regex.ReplaceAllString(str, repl) } return str }