Jun 10, 2012

Basic CQ5 code examples

Posted by Feike Visser

In this blogpost I will go through some sample code that you can use in your components, all samples are available out of the box.

So there is no need to write custom code in OSGi bundles for these samples.

Make sure you have this line at the beginning of your component:

<%@include file="/libs/foundation/global.jsp" %>

This global.jsp defines a set of global taglibs and makes a number of objects available that you can use via <cq:defineObjects/>. Documentation of the standard taglibs can be found here.

EL notations

In this set you see some samples how to display values from the objects available in your components. Via the EL-notation you can easily access methods from the objects.

display the name of the component


page name


resource page name



Next set is about properties and ways to use these in your component.

custom page property


custom page property (same as above)


property set via the Edit dialog


property set via the Edit dialog


print a property via cq:text

assigned property value to a var


If and For Each

This set is about doing an If-statement and doing a loop (For Each). 

listing sling selectors

${status.count}: ${item}

number of selectors


only show this if the page-name equals 'test'

this is a test page

page name not empty and length > than 10

pagename is not empty and more than 10


This set is about formatting, date format and simple String formatting.

length of page name


substring of page name


format date


The pageProperties object is an instance of the InheritanceValueMap, this adds two methods to the ValueMap interface:

getInherited( name, type );

getInherited( name, defaultValue);

This way you can get an inherited value with just one method call, no need for any custom code that gets an inherited value.

display the customProperty, via the inherited way

<%= pageProperties.getInherited("customProperty", "no value found") %>