Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: execute template methods directly #11

Merged
merged 6 commits into from
Sep 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ var (
ErrInvalidArg = errors.New("invalid argument")
// ErrTemplateCompilation is returned when a template fails to compile.
ErrTemplateCompilation = errors.New("template compilation failed")
// ErrFunctionNotFound Function does not exist in script.
ErrFunctionNotFound = errors.New("failed to find function")
)

// CallContext is the context that is passed to go functions when called from js.
Expand Down Expand Up @@ -160,6 +162,39 @@ func (e *Engine) RunScript(scriptFile string, data any) error {
return nil
}

// RunMethod enables calls to global template methods from easytemplate.
func (e *Engine) RunMethod(scriptFile string, data any, fnName string, args ...any) (goja.Value, error) {
vm, err := e.init(data)
if err != nil {
return nil, err
}

script, err := e.readFile(scriptFile)
if err != nil {
return nil, fmt.Errorf("failed to read script file: %w", err)
}

if _, err := vm.Run(scriptFile, string(script)); err != nil {
return nil, err
}

fn, ok := goja.AssertFunction(vm.Get(fnName))
if !ok {
return nil, fmt.Errorf("%w: %s", ErrFunctionNotFound, fnName)
}

gojaArgs := make([]goja.Value, len(args))
for i, arg := range args {
gojaArgs[i] = vm.ToValue(arg)
}
val, err := fn(goja.Undefined(), gojaArgs...)
if err != nil {
return nil, err
}

return val, nil
}

// RunTemplate runs the provided template file, with the provided data, starting the template engine and templating the provided template to a file.
func (e *Engine) RunTemplate(templateFile string, outFile string, data any) error {
vm, err := e.init(data)
Expand Down
Loading