Created

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

${component.name}

page name

${currentPage.name}

resource page name

${resourcePage.name}

Properties

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

custom page property

${pageProperties.customProperty}

custom page property (same as above)

${currentPage.properties.customProperty}

property set via the Edit dialog

${properties.myProperty}

property set via the Edit dialog

${properties["myProperty"]}

print a property via cq:text

assigned property value to a var

${newvar}

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

${fn:length(slingRequest.requestPathInfo.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

Formatting

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

length of page name

${fn:length(currentPage.name)}

substring of page name

${fn:substring(currentPage.name,0,5)}

format date

Inheritance

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") %>