Thursday, April 9, 2015

4 Ways to Try Javascript Use-API With Sightly


Here’s four exam­ples on how you can use the Javascript Use-API. You can already find some other exam­ples and doc­u­men­ta­tion on this Sightly doc-page.
Hello World
Let’s start with the ‘Hello World’ exam­ple, 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 exam­ple 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 exam­ple on how to use pre-defined objects within your Sightly-JS file. In this sam­ple I am sim­ply out­putting some val­ues 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
    };
});
Pass­ing argu­ments to the Sightly-JS file
In this exam­ple I will pass on some para­me­ters 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 ${ ” } nota­tion 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
    };
});
Pass­ing in Java-backed objects in your JS-files
In this last exam­ple I am pass­ing in a Java-backed object as a para­me­ter and call a method from that. Here I am using the xss­API, and call­ing 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 xss­API via this.xssApi and then call a method from it.
I hope you found these exam­ples use­ful and that they allow you to start using the Sightly JS-Use API. Let me know how it goes!

No comments: