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:

  1. Java Use API
  2. 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:

1. 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan