Search code examples
javascripthtmlapiaemsightly

Send arguments to use function in JS Use API | AEM 6.5


I am trying to get the url in my Javascript file. But seems like window.location work in JS Use API neither. So I was trying to send the URL as an argument but that's failing with an error. My JS code:

"use strict";
use(function () {
var url = this.url;
/other code/
});

My HTML code:

 <sly data-sly-use.item="'myfile.js' @ url=value">

Solution

  • HTL/Sightly is a server-side template language. The scripts (including JS Use Objects) are compiled and ran once, when the page is rendered. To get the current URL/location you can leverage SlingHttpServletRequest#getRequestPathInfo. The current request is available as request as part of the HTL Global Objects.

    Also, regarding getting errors when using <sly data-sly-use.item="'myfile.js' @ url=value">, that's most probably because value is not defined as a variable name in the HTL server-side rendering context. Using <sly data-sly-use.item="'myfile.js' @ url='https://www.test.com/'"> should work.