-1

I am using Sightly/HTL as the templating language in my AEM project (AEM version 6.3). As Sightly provides a lot of context objects, two of them being : request backed by org.apache.sling.api.SlingHttpServletRequest and currentSession backed by javax.servlet.http.HttpSession, I am trying to access some session parameter values in my sightly file by doing something like below:

${request.session.attribute @ mySessionAttribute}

or

${currentSession.attribute @ mySessionAttribute}

but am not able to get that value. Does anybody has any idea about how to do it?

Karttik Mishra
  • 150
  • 2
  • 14
  • This is not possible via HTL only, you’ll need to creat a java/js use class or preferably a sling model (easy to implement with samples from a quick google search) Also, please read the HTL specification https://github.com/Adobe-Marketing-Cloud/htl-spec/blob/master/SPECIFICATION.md – Ahmed Musallam Oct 11 '17 at 09:57

2 Answers2

1

In HTL/Sightly you cannot call arbitrary methods with parameters, it's a limitation by design. Since the javax.servlet.http.HttpSession API does not expose attributes as a map you can't access them as ${currentSession.attributes['mySessionAttribute']} so you will need to be creative about it:

script.html <sly data-sly-use.attr="${'attrib.js' @ session=currentSession, name='mySessionAttribute'}">${attr.value}</sly>

attrib.js use(function () { return { value: this.session.getAttribute(this.name) }; });

Vlad
  • 10,602
  • 2
  • 36
  • 38
1

You can not pass arguments to methods in HTL like this and I would not recommend doing it anyway.

One way to solve this issue is to use a Sling Model:

@Model(adaptables = SlingHttpServletRequest.class)
public SessionModel {

    @ScriptVariable
    private Session currentSession;

    public String getMySessionAttribute() {
        return this.currentSession.getAttribute("attributeName");
    }
}

HTL:

<div data-sly-use.sessionModel="com.mypackage.SessionModel">
    ${sessionModel.mySessionAttribute}
</div>
Jens
  • 20,533
  • 11
  • 60
  • 86