4 Ways to Try Javascript Use-API With Sightly
Here’s four examples on how you can use the Javascript Use-API. You can already find some other examples and documentation on this Sightly doc-page.
Hello World
Let’s start with the ‘Hello World’ example, to get a basic idea how the Use-API works.
I have this in my Sightly-component:
<div data-sly-use.hello="helloworld.js">
 ${hello.world}
</div>
And this is my helloworld.js
"use strict";
use( function () {
  var hello = "Hello World";
  return {
        // world can be used inside your component
        world: hello
    };
});
I hope this example is quite self-explanatory. ${hello.world} works because we define ‘hello’ in the use-api data-sly-use.hello, and ‘world’ is defined in the helloworld.js file.
Using pre-defined objects
Here an example on how to use pre-defined objects within your Sightly-JS file. In this sample I am simply outputting some values in order to show you how to use the pre-defined objects.
This is in my Sightly component:
<div data-sly-use.predefined="predefined.js">
 ${predefined.pageName}, 
 ${predefined.title}, 
 ${predefined.resourceName}, 
 ${predefined.resourceTitle}
</div>
This is my predefined.js file:
"use strict";
use( function () {
 
 var pageName = currentPage.name;
 var title = currentPage.properties.get("jcr:title");
 var resourceName = granite.resource.name;
 var resourceTitle = properties.get("jcr:title");
 
    return {
        pageName: pageName,
        title: title,
        resourceName : resourceName,
        resourceTitle : resourceTitle
    };
});
Passing arguments to the Sightly-JS file
In this example I will pass on some parameters to the Sightly-JS file.
This is my Sightly component:
<div data-sly-use.params="${ 'parameters.js' @ value1='feike', value2='visser', seperator=' '}">
 ${params.newValue}
</div>
Please note the ${ ” } notation to define the Use-API.
This is in my Sightly JS-script:
"use strict";
use( function () {
 
     // you can reference the parameters via this.
 var retValue = this.value1 + this.seperator + this.value2;
 
    return {
        newValue: retValue
    };
});
Passing in Java-backed objects in your JS-files
In this last example I am passing in a Java-backed object as a parameter and call a method from that. Here I am using the xssAPI, and calling the method encodeForXML().
This is my Sightly component:
<div data-sly-unwrap data-sly-use.encode="${ 'xmlEncoding.js' @ xssApi = xssApi, valueToEncode='hello world'}">
${encode.encodedValue}
</div>
This is my Sightly JS-file:
"use strict";
use( function () {
    return {
        encodedValue: this.xssApi.encodeForXML(this.valueToEncode)
    };
});
You can see how I access the xssAPI via this.xssApi and then call a method from it.
I hope you found these examples useful and that they allow you to start using the Sightly JS-Use API. Let me know how it goes!
No comments:
Post a Comment