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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With