How to pass the url dynamically in the data-sly-resource?

Viewed 132

I have 404.html page which has below:

<div data-sly-resource="/content/emc/en-us/errorhandler/404" data-sly-unwrap></div>

Also have a java class as below:

package apps.sling.servlet.errorhandler;

import com.adobe.cq.sightly.WCMUse;

public class ResponseStatus extends WCMUse {
    
    @Override
    public void activate() throws Exception {
        getResponse().setStatus(404);
    }
}

On status 404, it takes to 404 page (/content/emc/en-us/errorhandler/404). My requirement here is when the user is on en-us url, it should take to /content/emc/en-us/errorhandler/404. And if the user is on zh-cn url, it should take to /content/emc/zh-cn/errorhandler/404. I need to pass the urls dynamically in the data-sly-resource by reading the locale on the url. Can anyone help me with the script?

1 Answers

Let me share the way, it may help you.

Write a helper class:

import com.adobe.cq.sightly.WCMUsePojo;
import com.day.cq.wcm.api.Page;

public class PageNavigationHelper extends WCMUsePojo {
    private String locale;
    @Override
    public void activate() throws Exception {
        this.locale = get("locale", String.class);
    }
    public String getNotFoundUrl(){
        Page currentPage = getCurrentPage();
        String currentLocale = currentPage.getLanguage(true).getLanguage();

        // you can built more language specific url here.
        if(currentLocale.equalIgnoreCase("en")){
            return "/content/emc/en-us/errorhandler/404";
        }else{
            return "/content/emc/zh-cn/errorhandler/404";
        }
    }
}

Then into your HTML:

<div data-sly-use.langHelper="${'com.service.helper.PageNavigationHelper'}" data-sly-unwrap>
    <div data-sly-resource="${langHelper.getNotFoundUrl}" data-sly-unwrap></div>
</div>
Related