2019-03-18 13:34:52 +01:00
|
|
|
package filter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
|
2019-03-25 09:28:58 +01:00
|
|
|
"gitbase.de/apairon/mark2web/pkg/logger"
|
2019-03-19 11:15:32 +01:00
|
|
|
"gitbase.de/apairon/mark2web/pkg/mark2web"
|
2019-03-18 13:34:52 +01:00
|
|
|
"github.com/ddliu/motto"
|
2022-02-28 11:43:47 +01:00
|
|
|
"github.com/flosch/pongo2/v4"
|
2019-03-18 13:34:52 +01:00
|
|
|
_ "github.com/robertkrimen/otto/underscore"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RegisterFilters reads a directory and register filters from files within it
|
|
|
|
func RegisterFilters(dir string) {
|
|
|
|
files, err := ioutil.ReadDir(dir)
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Eexit(err, "could not read from template filters dir '%s'", dir)
|
2019-03-18 13:34:52 +01:00
|
|
|
for _, f := range files {
|
|
|
|
if !f.IsDir() {
|
|
|
|
switch path.Ext(f.Name()) {
|
|
|
|
case ".js":
|
|
|
|
fileBase := strings.TrimSuffix(f.Name(), ".js")
|
|
|
|
jsFile := dir + "/" + f.Name()
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.D("trying to register filter from: %s", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
/*
|
|
|
|
jsStr, err := ioutil.ReadFile(jsFile)
|
|
|
|
if err != nil {
|
|
|
|
Log.Panicf("could not read '%s': %s", jsFile, err)
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
vm := motto.New()
|
|
|
|
fn, err := vm.Run(jsFile)
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Eexit(err, "error in javascript vm for '%s'", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
if !fn.IsFunction() {
|
2019-03-29 15:49:25 +01:00
|
|
|
logger.Exit("%s does not contain a function code", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
err = pongo2.RegisterFilter(
|
|
|
|
fileBase,
|
|
|
|
func(in, param *pongo2.Value) (out *pongo2.Value, erro *pongo2.Error) {
|
|
|
|
thisObj, _ := vm.Object("({})")
|
2019-03-25 10:16:33 +01:00
|
|
|
var err error
|
2019-03-18 15:14:41 +01:00
|
|
|
if mark2web.CurrentContext != nil {
|
2019-03-25 10:16:33 +01:00
|
|
|
err = thisObj.Set("context", *mark2web.CurrentContext)
|
2019-03-18 13:34:52 +01:00
|
|
|
}
|
|
|
|
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Perr(err, "could not set context in '%s': %s", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
ret, err := fn.Call(thisObj.Value(), in.Interface(), param.Interface())
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Eexit(err, "error in javascript file '%s' while calling returned function", jsFile)
|
|
|
|
|
2019-03-18 13:34:52 +01:00
|
|
|
retGo, err := ret.Export()
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Perr(err, "export error for '%s'", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
return pongo2.AsValue(retGo), nil
|
|
|
|
},
|
|
|
|
)
|
2019-03-25 10:16:33 +01:00
|
|
|
logger.Perr(err, "could not register filter from '%s'", jsFile)
|
2019-03-18 13:34:52 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|