Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom Sling binding?

Tags:

jsp

aem

sling

I want to extend Sling bindings with a custom object, so it'll be available in all JSP files without an extra effort. I'm implementing BindingsValuesProvider OSGi service, like this (it's not an actual code, but similar enough):

@Component
@Service
public class ContentBranchBindingProvider implements BindingsValuesProvider {

    @Override
    public void addBindings(Bindings bindings) {
        final Resource resource = (Resource) bindings.get("resource");
        final String[] splitPath = StringUtils.split(resource.getPath(), '/');
        bindings.put("contentBranch", splitPath[1]);
    }
}

I expect that the contentBranch binding will be available as scripting variable in JSP:

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@include file="/libs/foundation/global.jsp"%>
Your content branch is: ${contentBranch}

However, above JSP doesn't output the content branch but:

Your content branch is:

I used debugger to see that my addBindings() method is called and puts a proper value into bindings map. What can I do to have it available as ${contentBranch} in JSP?

like image 467
Tomek Rękawek Avatar asked Jan 07 '15 16:01

Tomek Rękawek


1 Answers

Sling Bindings are not automatically available as scripting variables. There is a plan to change it to change it but in the current version of Sling they are not.

Sling uses <sling:defineObjects/> to copy its own bindings to the page context and therefore expose them as scripting variables, but it won't work for the custom values like contentBranch.

However, one of the scripting variables defined by the <sling:defineObjects/> is bindings, so you may access the new value like this:

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@include file="/libs/foundation/global.jsp"%>
Your content branch is: ${bindings.contentBranch}

Alternatively, consider writing a custom defineObjects tag.

Also, Sling bindings are available as scripting values in Sightly without any extra effort:

Your content branch is: ${contentBranch}
like image 63
Tomek Rękawek Avatar answered Oct 04 '22 03:10

Tomek Rękawek