Search code examples
javascriptaemsightly

Using AEM's Javascript Use-API, how can I pass a function to the HTL side and invoke it with arguments?


In Adobe AEM, say I have a Javascript Use-API file with this data being passed back:

File: secure.js

use( function() {
  var pages = ['home', 'about', 'contact'];

  return {
    pages: pages,
    isSecurePage: function(pageName) {
      return pages.indexOf(pageName) > -1;
    }
});

Then in HTL, how can I go about to invoke the isSecurePage method and pass it the argument required?

I've tried this:

File: home.html

<sly data-sly-use.secure="./secure.js" />

<div class="row" data-sly-list.child="${currentPage.listChildren}">
  <sly data-sly-test="${secure.isSecurePage(child.getName)}"> <!-- ERROR! -->
    <a href="${child.getPath}.html">${child.getName}</a>
  </sly>
</div>

But I get an error like this:

Parsing error in template ...

... extraneous input '(' expecting {'}', '.', '&&', '||', '[', '@'} for expression ${secure.isSecurePage( child.getName ) }


I've tried to rewrite them differently to see if I could invoke the method, but everything here fails:

1) secure.isSecurePage @ child.getName

2) secure.isSecurePage @ 'child.getName' )

3) secure.isSecurePage @ 0=child.getName )


While these ones below don't cause errors, it doesn't seem like it passes the parameters properly:

4) secure.isSecurePage @ first=child.getName )

5) secure.isSecurePage @ pageName=child.getName )

^ keeps returning false even though it should be true.

I'll try to figure out a way to log from the Javascript Use-API to investigate this further.

If anyone knows though, please help!

Thanks


Solution

  • You cannot call methods that take parameters in HTL. The only constructs that allow parameters are templates and the Use-objects instantiation. For more details check the data-sly-use [0] and Use-API [1] sections of the specification.

    [0] - https://github.com/adobe/htl-spec/blob/1.4/SPECIFICATION.md#221-use
    [1] - https://github.com/adobe/htl-spec/blob/1.4/SPECIFICATION.md#4-use-api