fixed #7, javascript filter for pongo2 with context in this variable
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
@@ -1,12 +1,21 @@
|
||||
package helper
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/flosch/pongo2"
|
||||
_ "github.com/flosch/pongo2-addons"
|
||||
"github.com/robertkrimen/otto"
|
||||
_ "github.com/robertkrimen/otto/underscore"
|
||||
)
|
||||
|
||||
func init() {
|
||||
pongo2.ReplaceFilter("markdown", MarkdownFilter)
|
||||
err := pongo2.ReplaceFilter("markdown", MarkdownFilter)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// MarkdownFilter is a pongo2 filter, which converts markdown to html
|
||||
@@ -19,3 +28,59 @@ func MarkdownFilter(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pong
|
||||
))),
|
||||
nil
|
||||
}
|
||||
|
||||
func RegisterFilters(dir string) {
|
||||
files, err := ioutil.ReadDir(dir)
|
||||
if err != nil {
|
||||
Log.Panicf("could not read from template filters dir '%s': %s", dir, err)
|
||||
}
|
||||
for _, f := range files {
|
||||
if !f.IsDir() {
|
||||
switch path.Ext(f.Name()) {
|
||||
case ".js":
|
||||
jsFile := dir + "/" + f.Name()
|
||||
Log.Debugf("trying to register filter from: %s", jsFile)
|
||||
jsStr, err := ioutil.ReadFile(jsFile)
|
||||
if err != nil {
|
||||
Log.Panicf("could not read '%s': %s", jsFile, err)
|
||||
}
|
||||
vm := otto.New()
|
||||
fn, err := vm.Run(jsStr)
|
||||
if err != nil {
|
||||
Log.Panicf("error in javascript vm for '%s': %s", jsFile, err)
|
||||
}
|
||||
if !fn.IsFunction() {
|
||||
Log.Panicf("%s does not contain a function code", jsFile)
|
||||
}
|
||||
|
||||
err = pongo2.RegisterFilter(
|
||||
strings.TrimSuffix(f.Name(), ".js"),
|
||||
func(in, param *pongo2.Value) (out *pongo2.Value, erro *pongo2.Error) {
|
||||
thisObj, _ := vm.Object("({})")
|
||||
if currentContext != nil {
|
||||
thisObj.Set("context", *currentContext)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
Log.Panicf("could not set context as in '%s': %s", jsFile, err)
|
||||
}
|
||||
ret, err := fn.Call(thisObj.Value(), in.Interface(), param.Interface())
|
||||
if err != nil {
|
||||
Log.Panicf("error in javascript file '%s' while calling returned function: %s", jsFile, err)
|
||||
}
|
||||
retGo, err := ret.Export()
|
||||
if err != nil {
|
||||
Log.Panicf("export error for '%s': %s", jsFile, err)
|
||||
}
|
||||
return pongo2.AsValue(retGo), nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
Log.Panicf("could not register filter from '%s': %s", jsFile, err)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user