Showing posts with label Sightly. Show all posts
Showing posts with label Sightly. Show all posts

Saturday, 22 April 2017

Hashmap in Sightly / HTL

Use hashmap in sightly / HTL

WCMUsePojo code
package com.kishore.sightly;

public class GetMap extends WCMUsePojo {
    Map<String, String> myMap = null; 
    public void activate() throws Exception {
        myMap = new HashMap<String, String>();
        myMap.put("name", "Kishore");

    public Map<String, String> getmyMap() {
            return myMap;

HTL code

<sly data-sly-use.model="com.kishore.sightly.GetMap" />

Name: ${model.myMap['name']}

Saturday, 25 March 2017

Access OSGI ser­vice from the WCMUse-class in Sightly

OSGI service are very helpful once its comes to the development of a module. A Service can be used to perform small task like string operations to big like processing shopping cart. For developers who are shifting to Sightly for better development practices and taking advantage of AEM 6.x features, it might be a troublesome that how a OSGI Service can be accessed in Sightly module.
Zoom out a bit and you will be able to see things more clear. Here’s all that needs to be done,
  1. You have to create a OSGI service as usual by creating a interface and implementing it.
  2. Create a class extending WCMUse and get the instance of your OSGI service. 
  3. Class created in step #2, use this in Sightly component to get the values / output

Friday, 17 February 2017

Uncaught ReferenceError: CQ is not defined

To avoid this error add init.jsp or init.html in your code.
<sly data-sly-include="/libs/wcm/core/components/init/init.jsp" data-sly-unwrap/>

Sidekick is not loading in AEM

We can hide/disable sidekick in author mode in page component by removing/commenting or by not including "/libs/wcm/core/components/init/init.jsp" in any of the jsps of the page or its super/parent resource.

In Sightly we can use below code
<sly data-sly-include="/libs/wcm/core/components/init/init.jsp" data-sly-unwrap/>

Creating a site footer in AEM 6 using Sightly and Sling Models

The Adobe-developed and recently-donated-to-Apache-Sling project Sightly project has been out for a little under a year now, alongside Adobe Experience Manager 6, and has slowly been amassing documentation and gaining presence. The server-side templating language aims to give a facelift to the web development facet of Java-based software stacks, Adobe's AEM chief among them.
This post will run the reader through a sample implementation of a site footer using Sightly, showcasing and describing a few of its features. It will also make use of Sling Models as the back-end tool to grab JCR data (nodes, properties) into useful class models.
What we want is an authorable footer serving all pages of a language branch of a content tree. Let's assume that our site is for Acme, the reputable maker of all things widgets, gadgets, and sprockets. Our site structure will be traditional and look like,
and so on. Let's assume that the en page serves as the homepage for the English site, and similarly, the /content/acme/fr will serve as the French homepage, with all French content pages under it. As such, each homepage will need to have an instance of footer data.

Sightly/HTL Javascript Use Class Logging

Sightly Log Filter

This tool makes it easier to filter out log messages in the error.log for just messages generated by your Javascript Sightly Use Classes.


You can use the file standalone in the logs directory by performing a chmod +x on the file, then running the file as so:
./ myUseClass.js
Optionally you could alias this and just call the command.
This tool is covered by the LICENSE file at the root of this repository.
The readme and use of the helper bash script should be sufficient to get you up and running in no time. The installation is very straightforward, just drop the script into the log directory of your AEM instance, chmod to allow execution, and then start viewing your JS Use class logs! An alternative approach is to alias it, then use it as a standalone command.

Thursday, 11 August 2016

Sightly – Quick Reference

Sightly was introduced by AEM 6.0 to replace JSP by a new HTML Templating System. This post is a quick reference about Sightly. A list of best practices and things to know.
Java class or server side Javascript
With Sightly, you can create a component with two methods. By using Java Class or Javascript Server-Side File. Personnaly, I always use Java Class, but Javascript seems to be a really good deal if you want to develop your components with one language. But keep in mind that AEM Java API offer more functionnalities than Javascript API.
  • Sigthly component with Java
package apps.mycomponent;
import com.adobe.cq.sightly.WCMUse;
public class MyComponent extends WCMUse {
    private String title;
    private String description;
    public void activate() throws Exception {
        title = getProperties().get("title", "");      
        description = getProperties().get("description", "");
    // Must have to get back the value in html file
    // Explanation : 'get' + capitalize method name
    public String getTitle() {
        return title;
    public String getDescription() {
        return description;

HTL (Sightly) Code Snippets

Below are few HTL syntax used frequently in AEM.

1. HTL does not support JSP tag libraries.

2. Including a script: data-sly-include instead of cq:include

<cq:include script="template.html"/> //Including a HTL file in JSP
<sly data-sly-include="template.jsp"/> //Including a JSP file in HTL

The element on which a data-sly-include has been set is ignored and not displayed.

3. Including a Resource: data-sly-resource

Includes the result of rendering the indicated resource through the sling resolution and rendering process. Basic syntax-

<article data-sly-resource="path/to/resource"></article>

Override resourceType of an include-
<article data-sly-resource="${'path/to/resource' @ resourceType='my/resource/type'}"></article>

Change the wcmmode-
<article data-sly-resource="${'path/to/resource' @ wcmmode='disabled'}"></article>

Sunday, 31 July 2016

Developing HTML Template Language Components that search for AEM Content Tags

You can create a custom Adobe Experience Manager (AEM) HTL component that searches for AEM content tags. Tags are a quick and easy method of classifying content within your website. In technical terms, a tag is a piece of metadata assigned to a content node within AEM (usually a page). Within the OSGi component, the AEM Tag Manager is used to search for the content tags, For information about the API, see TagManager API.For information about the API, see AEM TagManager.
Consider the following illustration of the HTL component created in this article that shows defined AEM tags. 

Friday, 24 June 2016

Creating an AEM Sightly component that uses JavaScript

You can create an Adobe Experience Manager (AEM) Sightly component that uses JavaScript. By using JavaScript as part of your Sightly component, you can create a more dynamic component that responds to events such as when the user scrolls over text with the mouse. For example, you can change the background color an AEM web page, as shown in the following illustration. 
An AEM Sightly component that uses JavaScript

Thursday, 28 April 2016

Learn Sightly with Read–Eval–Print Loop in AEM 6.x

A great live code editing environment for Sightly templates with optional server-side JavaScript logic, executed on an Adobe Experience Manager instance. This little tool is great for learning Sightly and for experimenting with it, because the resulting output is displayed as you type.
To get started you need minimum Adobe Experience Manager 6+, there are you two ways you can setup your environment and start experimenting:-
1. Install as a Package
  • Download the built package:
  • On your running AEM instance, go to Package Manager, click on Upload Package, browse to the previously downloaded package, and hit OK.
  • Install the package Don’t mind the missing dependencies, simply click the Install button and confirm.
2. Maven Method
  • Checked-out repository with Git clone.
  • Build and install it with following command line instruction:
    mvn clean install content-package:install
Once any of the above steps are performed for installation, go to the following URL on AEM instance localhost:4502/content/repl.html
Sightly Read Eval Print Loop (REPL)
Sightly Read Eval Print Loop (REPL) will give you three options:-
  1. Source :- Shows the generated HTML Structure of webpage
  2. View :- Output of webpage can be seen here, this is the same which you will see in your browser
  3. Java :- Complied sightly Java class
It’s a great environment for people who are willing to get hands on Sightly and want to gain some experience in it.

Saturday, 26 March 2016

Implement DataSource for drop down using Sightly AEM 6.1

In Touch UI component, DataSource is very useful when it comes populate drop down dynamically. This article will help you to understand how datasource can be used with Sightly and leaving JSP behind.
Let’s get started with authoring…
Sightly DataSource Component Authoring
Component contains a simple drop down, values for this will be populate dynamically using DataSource.

Monday, 11 January 2016

Implement Use-Interface using Sightly in AEM 6.x

Implementing sightly can be basically done with two important APIs (although few others are also available). In my other article I have cover up how you can  Access OSGI ser­vice from the WCMUse-class in Sightlyhere we are going to cover next important one which shows how you can implements the Use-interface in Java and combine your business logic with component file. 
Let’s see Use interface first, later we will jump to code. 
All you need to make sure is to implement public void init(javax.script.Bindings bindings) The initmethod will be called on initialization of the class with a Bindings object that holds all the context objects and any parameters passed into the use-class. Business logic will be present in this method, although you are free to create custom method which will be called from init().
Binding object is an mapping of key/value pairs, all of whose keys are Strings.

Sunday, 6 December 2015

JavaScript Use-API with 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.

 Read More

Thursday, 19 November 2015

Creating a Sightly component that uses the AEM QueryBuilder API

You can create an Adobe Experience Manager (AEM) 6 Sightly  component that can be used within the AEM Touch UI view. Furthermore, you can use Sightly and the QueryBuilder API to develop the AEM component that displays AEM JCR data.

Sightly is an AEM  template language that can be used to replace the use of JSP when developing an AEM component. Sightly helps you to separate your design from your application logic.  In this use case, the Sightly logic is located within an HTML file and displays the result set. The Java part of the Sightly component uses the QueryBuilder API.

To read this AEM community article, click

Wednesday, 18 November 2015

AEM Touch UI issues

When working with AEM touch ui we often come across some issues. Below are some of the common issues which we face when using touch ui.

<cq:include path=’text’ resourceType=’foundation/components/text’/> 
In Sightly, you can do a similar one-liner:

<div data-sly-resource=${‘text’ @resourceType=’foundation/components/text’}”></div>
However, there are a few things to be aware of when embedding components, especially when using Touch UI.
I will highlight three issues that I have come across when embedding components using Sightly and Touch UI, and explain the symptom, the cause, and give a solution for each.
ISSUE 1: Edit config does not refresh page after component edit
The Symptom 
A component set up to refresh the page after edit does not refresh the page in Touch UI. In the web console there is a JavaScript error: Uncaught TypeError: Cannot read property ‘componentConfig’ of undefined.
The Cause
The component was in the .hidden component group. Touch UI has a list of editables, or components. This list does not include components in the .hidden group. When the component is edited, JavaScript runs that looks for the component in the list of editables. Because it is not in the list, the JavaScript throws an error and the editconfig afteredit action does not happen.
Uncaught TypeError: Cannot read property 'componentConfig' of undefined
The Solution
Put the component in a group other than .hidden. This will make the component available to be added to the list of components that can be dropped into a parsys, and it would be up to the content team to not include these components in the design configuration. To help keep this clear you could put the components into a group named Hidden.
Note: I am continuing to look for a good solution to handle components in the .hidden group, since the parsys component is in that group and in my experience is the most common component to be embedded. So far I have not yet found a way to deal with this. It appears in Touch UI there is an update method that runs after closing the dialog, and that supersedes any custom afteredit event handlers attached to the component.
ISSUE 2: Dialog does not open in Touch UI
The Symptom
Embedded component’s dialog box doesn’t open in Touch UI. In the web console there is a 400 (Bad Request) error.
The Cause
Embedded components do not create their content node until after the dialog has sent a POST to the component’s content path. The problem here is that in Touch UI the component looks for the dialog to open based on the content path. Since the content path doesn’t exist the dialog fails to open with an error.
The Solution
Make sure the content node for the component exists. There are a couple ways of doing this.
  1. Add the component to the jcr:content of the template used to create the page.
  2. Add a script to run just before the include of the component that creates the node if it doesn’t already exist. (Below is some example code For solution 2)
In a file named EmbeddedComponent.js
"use strict";
 * Creates a component node with name, if node does not yet exist.
use([], function () {
    var newResourceName =;
    var newResourceType = this.type;
    var resourceResolver = resource.getResourceResolver();
    var newNodePath = resource.path + "/" + newResourceName;
    var existingComponentResource = resourceResolver.getResource(newNodePath);
    if(existingComponentResource == null){
        var properties = {"jcr:primaryType":"nt:unstructured",
        resourceResolver.create(resource, newResourceName, properties);
Sightly script

<div data-sly-use="${EmbeddedComponent.js' @ name='primary', type='foundation/components/parsys'/> 
Java Use API

package com.aempodcast.example.components.utils;
import com.adobe.cq.sightly.WCMUse;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmbedComponent extends WCMUse {
    private static final Logger log = LoggerFactory.getLogger(EmbedComponent.class);
    private ResourceResolver resourceResolver = null;
    private String resourceType = null;
    private String resourceName = null;
    private Resource resource = null;
    private Resource child = null;
    public void activate() throws Exception {
        // Set resource Name and Type
        resourceName = get("name", String.class);
        resourceType = get("type", String.class);
        resource = getResource();
        child = resource.getChild(resourceName);
        resourceResolver = resource.getResourceResolver();
        if (child != null && !child.isResourceType(resourceType)) {
        } else if(child == null) {
    private void createResource() {
        try {
            Map<String, Object> properties = new HashMap<>();
            properties.put("sling:resourceType", resourceType);
            resourceResolver.create(resource, resourceName, properties);
        } catch (PersistenceException ex) {
            log.error("Failed to create resource", ex);
    private void updateResourceType() {
        try {
            Node childNode = child.adaptTo(Node.class);
            childNode.setProperty("sling:resourceType", resourceType);
        } catch (RepositoryException ex) {
            log.error("Failed to update resource type", ex);
    private void commitChanges() {
        try {
        } catch (PersistenceException ex) {
            log.error("Failed to save changes", ex);
Sightly Script

<div data-sly-use="${com.aempodcast.example.components.utils.EmbedComponent' 
@ name=’primary’, type='foundation/components/parsys'}" data-sly-resource="primary"></div>
ISSUE 3: Component select highlight goes beyond the component area
The Symptom
Embedded component’s authoring highlight in Touch UI is bigger than the component itself, or an embedded component below is un-editable.
HighlightGoesBeyondSymptomEach paragraph is a copy of a component. The top most is embedded while the other four are dropped into parsys. The embedded component has data-sly-unwrap set on it. The blue border shown is the selected top most component. The other four components cannot be selected.
The Cause
The wrapping element of the component had been removed with data-sly-unwrap. Adobe Experience Manager puts a cq element, which holds helpful metadata for the authoring interface. One of the things it is used for is to set which element to use as the component boundary. When the component is selected, the boundary gets highlighted with a blue border. When the default wrapping element is removed, the next parent element is then used as the component boundary, which can cause the highlight to go beyond the component, and interfere with the ability to edit other components.
The Solution
Do not use data-sly-unwrap on elements including data-sly-resource.
In transitioning from CQ5 JSPs and the Classic UI to Adobe Experience Manager 6.0 Sightly and Touch UI, there are things that need to be adjusted in how they are done. Knowing the possible issues–and how to solve them–will make Sightly and Touch UI easier to use for developers and content authors.

Friday, 13 November 2015

How to include clientlibs in you component using Sightly AEM

How to use client libs in Sightly

First you should declare data-sly-use.clientlibInclude in your .html file

<div data-sly-use.clientlibInclude="${'/libs/granite/sightly/templates/clientlib.html'}"></div>

how to  include only CSS of clientlib 

<output data-sly-call="${clientlibInclude.css @ categories='clientlib1,clientlib2'}" data-sly-unwrap/>

how to  include only JS of clientlib 

<output data-sly-call="${clientlibInclude.js @ categories='clientlib1,clientlib2'}" data-sly-unwrap />

how to  include both CSS and JS of clientlib 

<output data-sly-call="${clientlibInclude.all @ categories='clientlib1,clientlib2'}" data-sly-unwrap />

Sightly vs Handlebars vs JSP: Comparing Scripting Languages

The latest release of Adobe Experience Manager, version 6.0, introduces two new languages for front end scripting in CQ.   The two languages are both attempting to address the problems found in the existing foundation and Geometrixx reference code, namely the lack of separation of concerns between business and presentation logic and the sloppy use of scriplet.  
The two new templating languages are:


Sightly has come from Adobe user groups and seems to be trumpeted by the Adobe Professional Services team.  There is official documentation for Sightly and Adobe has produced a number of blog posts and webinars about it:
Essentially, Sightly extends HTML5 adding a number of data attributes for server side processing.  These attributes support basic logic and writing content to the page.


Handlebars is based mostly from the Adobe Social Communities project.  Essentially, the Social Communities team took the Java implementation of the Handlebars JS Library to Java and added some hooks into AEM.  There is a JavaDoc API and documentation of the Social Component Framework, but as of yet, there does not seem to be any reference on the AEM specific features in Handlebars.


We'll lets go ahead and take a simple task in JSP and see what it looks like in each scripting language.  


This code block below would be found in a JSP script called mycomponent.jsp in a component at the path /apps/myapp/components/mycomponent.  This component outputs the title property, then if the layout is set to left it will include the component at the subpath left and otherwise the omponent at the subpath right.
     <c:when test="${properties.layout = 'left'}">
       <cq:include path="left" resourceType="myapp/components/mycomponent/layouts/left" />
       <cq:include path="right" resourceType="myapp/components/mycomponent/layouts/right" />


In Sightly the code would exist in a file at the same path with the name mycomponent.html.  The code would look like:
   <div data-sly-test="${properties.layout == 'left'}">
     <div data-sly-resource="${'left' @ resourceType='myapp/components/mycomponent/layouts/left'}"></div>
   <div data-sly-test="${properties.layout != 'left'}">
     <div data-sly-resource="${'right' @ resourceType='myapp/components/mycomponent/layouts/right'}"></div>


In Handlebars the code would exist in a file at the same path with the name mycomponent.hbs.  Unlike the other templating languages, handlebars is billed as being 'logicless'; practically what this means is you can't do some typical things like comparisons in the if statement.  The code would look like:
  <h2>{{ title }}</h2>
  {{#if layoutLeft}}
    {{include 'left' resourceType='myapp/components/mycomponent/layouts/left'}}
    {{include 'right' resourceType='myapp/components/mycomponent/layouts/right'}}


Each language has it's own advantages and disadvantages, below is a feature comparison for the different languages:
Based on Published Standards / Open Source?Y (*)NY
IDE Support?YNN
Officially Documented / Supported?YYY
Documented Extension Model?YNN
Includes XSS escaping?Y (**)YN
Allows Basic Logic?YYY (***)
Enables Bad Coding Practices?YNN
* - Some proprietary TagLibs used for interacting with CQ
** - Provided by additional tag libraries
*** - Yes-ish, but very limited


In the end, each scripting language has it's strengths and weaknesses, but JSP is the clear winner.  Yes, you can develop (and Adobe/Day has developed) really bad code with scriptlet, but given the extensibility, universal support, longevity and number of pre-existing examples, JSP is heads above the other scripting languages.  Sightly is very young and likely immature, lacks a published standard and offers disadvantages when trying to figure out what is plain markup and what is logic code.  Handlbars starts with a well documented Open Source project, but the CQ-specific extensions are not documented and it does not seem to be supported by the entire Adobe team.