A use-class for passing and accessing request attributes between HTL script and resource includes.
Traditionally, additional parameters couldn't be passed to script (data-sly-include) or resource (data-sly-resource) includes in HTL.
In 6.3, AEM introduced the ability to add requestAttributes, provided by a use-class.
This implementation combines the setting of requestAttributes (with a specified prefix, or default "default_") with a map-interface for retrieving any request attributes.
Setting Attributes
The attributes are specified in the data-sly-use expression, passing the arguments we want to add. In order to add the provided arguments as requestAttributes, we invoke the save()
method in the data-sly-include
or data-sly-resource
. The use-class will not automatically save the provided arguments unless save()
is invoked.
<sly data-sly-use.attributes="${'com.example.use.RequestAttributesHelper' @ default_text='This is a title'}"
data-sly-resource="${'heading' @ requestAttributes=attributes.save} />
The default prefix for arguments to be added as request attributes is "default_", but the prefix can be specified with parameter prefix. Any other arguments which don't start with the prefix will be ignored.
<sly data-sly-use.attributes="${'com.example.use.RequestAttributesHelper' @ prefix='_', _text='This is a title'}"
data-sly-resource="${'heading' @ requestAttributes=attributes.save} />
If you want to add all bindings (that the use-class was initialized with), you can specify an empty prefix.
Note: the bindings will contain a lot more entries than just your provided arguments, so this is generally not something you want to do. This ability exists as a helper during development.
<sly data-sly-use.attributes="${'com.example.use.RequestAttributesHelper' @ prefix='', heading_text='This is a title'}"
data-sly-resource="${'heading' @ requestAttributes=attributes.save}/>
Usage for data-sly-include
is identical.
<sly data-sly-use.attributes="${'com.example.use.RequestAttributesHelper' @ default_text='This is a title'}"
data-sly-include="${'heading.html' @ requestAttributes=attributes.save} />
Accessing Attributes
All request attributes can be accessed with this use-class. It implements Map, so the attributes can be accessed directly from the use-object.
Note: this use-class is not a real Map implementation and should not be expected to work in that way. It only implements get() and keySet(), to support property access in HTL.
<h1 data-sly-use.attributes="com.example.use.RequestAttributesHelper">${properties.text || attributes.default_text}</h1>
Any request attribute can be accessed through this helper. This is provided as a utility, and is not necessarily the recommended approach.
<p data-sly-use.attributes="com.example.use.RequestAttributesHelper">WCM mode: ${attributes.wcmmode}</p>