April 7, 2020
Estimated Post Reading Time ~

JavaScript Use-API with a Simple component in Sightly

The Sightly JavaScript Use-API enables a Sightly file to access helper code written in JavaScript (server side execution). This allows all complex business logic to be encapsulated in the JavaScript code, while the Sightly code deals only with direct markup production.

A simple use of JavaScript Use-API can be be seen here. These are predefined method defined in sightly, those can be used in JS file to read the values and return it. Example has been shown with a simple component which excepts a title and description. These values are then read by server side JS using available Use API. Once read they will be returned to component sightly file for rendering in html.

Let’s get started,

1. Create a component with same dialog structure as shown below 
<dialog jcr:primaryType="cq:Dialog" xtype="tabpanel">
<items jcr:primaryType="cq:WidgetCollection">
<title-desc jcr:primaryType="nt:unstructured" autoScroll="true" height="1200" title="Relates Articles" width="1200" xtype="panel">
<items jcr:primaryType="cq:WidgetCollection">
<title jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Title" name="./title" xtype="textfield"/>
<desc jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Description" name="./description" xtype="richtext"/>
</items>
</title-desc>
</items>
</dialog>

2. Create two files as shown in below image with name sightly-component.html and sightly-component.js



3. Use the following code in sightly-component.js
"use strict";

use(function() {
 var Constants = {
  TITLE: "title",
  DESCRIPTION_PROP: "description",
 };

 var title = properties.get(Constants.TITLE, "")
 var description = properties.get(Constants.DESCRIPTION_PROP, "");

 return {
  title: title,
  description: description
 };
});

Line 9 – 10 :- Reading values stored in JCR after authoring
Line 13 – 14 :- Return title and description to sightly file ( sightly-component.html )

4. Use following code in sightly-component.html
<div data-sly-test="${wcmmode.edit}"><p class="text-warning">--- Author the component ---</p></div>
<div data-sly-use.data="sightly-component.js"> 
    <sly data-sly-test="${data}">    
    <span class="label label-info">Title</span> <br>
    ${data.title}
<br>
    <span class="label label-info">Description</span> <br>
    ${data.description @ context='html'}
    </sly>
</div>

Line 2 :- Reading returned values from JS file
Line 5, 8 :- Output the title and description. As description was authored using richtext, we are using ‘html’ context to render.

5. Author the component



6. That’s it, you can see the title and description on the page



This shows a simple use case with JavaScript Use API, we will cover much more details in upcoming articles.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.