As of version 2.0.14 of Sling Scripting Core, Sling Scripting allows bundles to contribute objects to the variables available to scripts by exposing OSGi services.
This can be done by implementing either java.util.Map
or org.apache.sling.scripting.api.BindingsValuesProvider
. Implement org.apache.sling.scripting.api.BindingsValuesProvider
if you need access to the current script variables.
In either case, implementations are able to add one or more name/value pairs to the javax.script.Bindings
object, but they cannot overwrite or remove any of the default scripting variables (defined here: Scripting Variables). These custom bindings can be configured to apply to any scripting language or a specific scripting language.
An example of the binding of a custom object using java.util.Map
can be found in the extensions.groovy bundle (source):
import org.apache.sling.commons.json.groovy.JSONGroovyBuilder; /** * BindingsValuesProvider which binds an instance of JSONGroovyBuilder. * * @scr.component immediate="true" metatype="no" * @scr.service * * @scr.property name="service.description" value="JSONGroovyBuilder BindingsValuesProvider" * @scr.property name="service.vendor" value="The Apache Software Foundation" * * @scr.property name="javax.script.name" value="groovy" */ public class JSONGroovyBuilderBindingsValuesProvider extends HashMap<String,Object> { public JSONGroovyBuilderBindingsValuesProvider() { super(); put("jsonBuilder", new JSONGroovyBuilder()); } }
In this example, the jsonBuilder
key is bound to an instance of JSONGroovyBuilder
only for Groovy scripts.
An example of the binding of a custom object using org.apache.sling.scripting.api.BindingsValuesProvider
can be found in the jcr.resource bundle (source):
import javax.jcr.Node; import javax.script.Bindings; import org.apache.sling.api.resource.Resource; import org.apache.sling.scripting.api.BindingsValuesProvider; /** * BindingsValuesProvider for currentNode object. * * @scr.component immediate="true" metatype="no" * @scr.service * * @scr.property name="service.description" value="CurrentNode BindingsValuesProvider" * @scr.property name="service.vendor" value="The Apache Software Foundation" * * @scr.property name="javax.script.name" value="any" */ public class CurrentNodeBindingsValuesProvider implements BindingsValuesProvider { /** * {@inheritDoc} */ public void addBindings(Bindings bindings) { Resource resource = (Resource) bindings.get("resource"); Node node = resource.adaptTo(Node.class); if (node != null) { bindings.put("currentNode", node); } } }
1 Comment
Ahmed Musallam
Justin Edelson Excellent wiki page!
The link to CurrentNodeBindingsValuesProvider.java is no longer valid, I believe that class was replaced with this one: JcrObjectsBindingsValuesProvider.java
Also, the JsonBuilderBindingsValuesProvider.java class you referenced was moved to contrib, new link here: