AEM JavaScript Use API
JavaScript Use API helps us to access JavaScript code inside HTL.
Use API also allows us to access server side code using JavaScript.
There are two types of Use API:
- Java Use API
- JavaScript Use API
Example
Let’s create an AEM component to consume JavaScript Use API beneath below highlighted component hierarchy as part of current implementation:
Please follow below steps to create a component in AEM:
- Navigate to ui.apps/src/main/content/jcr_root/apps/practice/components folder and create a custom folder. In our case or for current tutorial it is practice.
2. Create file .content.xml inside practice folder created in first step and paste below content:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:Component"
jcr:title="Practice"
componentGroup="Practice"/>
jcr:primaryType is to create a node of type cq:component.
jcr:title is to declare component title.
componentGroup is use to group component under one category.
3. Create _cq_dialog folder inside practice folder created in first step. Create .content.xml file inside _cq_dialog folder and paste below component.
In below inline file provided two authorable fields to author Title and Description.
4. Create JavaScript file under below hierarchy as shown below:
5. Paste below content inside JavaScript API
"use strict";use( function() {var data = {}; data.pageTitle = currentPage.properties["jcr:title"]; data.title = granite.resource.properties["title"];
data.description = granite.resource.properties["description"]; return data;});
6. Create practice.html file having same folder name of practice.
Access practice.js JavaScript file using data-sly-use tag.
7. Create page, drag and drop practice component on the page. Click on Drag components here option as shown below:
8. Open page and select Practice component option as highlighted below:
9. Select practice component and click on below highlighted button to author practice component
10. Author Practice Component, fill title and description. Click on ok button highlighted red in color.
11. Below is the output for Practice component after authoring.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.