我有一个页脚元素,需要共享。我的计划是在父/主页上设置页脚,但允许子页覆盖这些属性。
我首先查看属性的当前组件(相当标准),然后获得父页面的路径,以查找具有相同名称的组件上的属性。
function getProperty(property, currentPage) {
var val = null,
page = currentPage,
rootPage = page.getAbsoluteParent(2);
var curNode = currentNode.getPath(),
nodeStrIdx = curNode.indexOf("jcr:content"),
nodeStr = curNode.substr(nodeStrIdx + 12); // Remove 'jcr:content/' too
while(val == null) {
// If we've gone higher than the home page, return
if(page.getDepth() < 3) {
break;
}
// Get the same node on this page
var resource = page.getContentResource(nodeStr);
if(resource != null) {
var node = resource.adaptTo(Node.class); // *** This is null ***
// val = node.get(property);
}
// Get the parent page
page = page.getParent();
}
return val;
}
我已经看到,您可以将内容资源的类型更改为一个节点,该节点允许我获得相同的property
,但resource.adaptTo(Node.class)
返回的是null。
如果不清楚,resource
是指向我想要从/content/jdf/en/resources/challenge-cards/jcr:content/footer/follow-us
中提取属性的绝对路径
发布于 2017-08-04 20:19:03
假设您使用的是HTL使用API,您需要使用完全限定的名称作为Java类,如下所示:
var node = resource.adaptTo(Packages.javax.jcr.Node);
然后,您可以以这种方式检索您的值:
if (node.hasProperty(property)) {
val = node.getProperty(property).getString();
}
您需要在每个节点API中使用节点API方法,因为在缺少属性时,getProperty
抛出PathNotFoundException
。您还需要小心处理示例中的granite.resource对象--它不是同一个Resource,它没有adaptTo
方法。要访问组件的原始资源,需要使用nativeResource
属性:
var node = granite.resource.nativeResource.adaptTo(Packages.javax.jcr.Node);
但是,也应该有一种更快的方法从JS中的资源中获取属性:
val = resource.properties[property];
由于这是开发组件属性继承的一个非常常见的情况,您还可以在实现设计中考虑一些现成的解决方案,如HierarchyNodeInheritanceValueMap API或继承段落系统(iparsys)。
由于这个JS是用莫兹拉犀牛编译的服务器端,这里使用的所有这些对象和方法都是HierarchyNodeInheritanceValueMap对象和方法,所以您也应该能够以这种方式使用HierarchyNodeInheritanceValueMap:
//importClass(Packages.com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap);
//this import might be needed but not necessarily
var props = new HierarchyNodeInheritanceValueMap(granite.resource.nativeResource);
val = props.getInherited(property, Packages.java.lang.String);
然后,它将返回当前资源的属性值,如果为空,则返回位于父页上相同位置的资源的属性值,如果为空,则返回给val
。这两行将执行所有的操作。
https://stackoverflow.com/questions/45501831
复制相似问题