Skip to content
/ gojst Public

Quick and dirty Golang-Javascript Template and Expression Evaluator

Notifications You must be signed in to change notification settings

Oberonus/gojst

Repository files navigation

Golang-Javascript Template and Expression Evaluator

Build Status Go Report Card codecov

import "github.com/oberonus/gojst"

Quick and dirty wrapper around otto javascript interpreter to give a power of ES5 to the goland template engine.

Quick Example

Initialization

//get your favourite javascript file
script := `
    function mul(arg1, arg2) {
        return arg1 * arg2;
    }
`
//initialize external variables
vars := map[string]interface{}{
    "v1": 3,
    "v2": 4,
}
//create new engine
eng, err := gojst.NewEngine(strings.NewReader(script), vars)
if err != nil {
    panic(err)
}

Evaluating Expressions

//execute javascript expression
res, err := eng.EvalString(`"vars: " + data.v1 + " and " + data.v2`)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%v\n", res)

Will print:

vars: 3 and 4

Rendering templates

//run template renderer
res, err := eng.Render(`multiplication of two variables: {{.C "mul" .D.v1 .D.v2}}`)
if err != nil {
    log.Fatal(err)
}
//will print ""
fmt.Printf("%v\n", res)

Will print:

multiplication of two variables: 12

Usage in templates

Reaching javascript functions and internal/external variables from template

Call javascript function

    {{.C "function" param1 param2 ...}}

Getting internal variables from javascript engine

    {{.V "variable"}}

Getting external variables from provided map

    {{.D.variable}}

About

Quick and dirty Golang-Javascript Template and Expression Evaluator

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published