AEM 6.2从父页面获取组件属性

问题描述:

我有一个需要共享的页脚元素。我的计划是在父/主页上设置页脚,但允许子页面覆盖这些属性。AEM 6.2从父页面获取组件属性

我首先查看当前组件的属性(非常标准),然后获取父页面的路径以查找组件上具有相同名称的属性。

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; 
} 

我已经看到了你可以在内容资源的类型更改为这应该让我得到同样的propertyresource.adaptTo(Node.class)被返回空的节点。

如果不明确,resource是我想要从属性中提取属性的节点的绝对路径。 /content/jdf/en/resources/challenge-cards/jcr:content/footer/follow-us

假设你正在使用Javascript HTL Use API,你需要为Java类使用完全合格的名称,如:

var node = resource.adaptTo(Packages.javax.jcr.Node); 

然后你就可以通过这种方式获取你的价值:

if (node.hasProperty(property)) { 
    val = node.getProperty(property).getString(); 
} 

你需要使用hasProperty方法每Node API作为getProperty抛出PathNotFoundException当一个属性丢失。您还需要注意来自示例的granite.resource对象 - 它与Resource对象不同,并且没有adaptTo方法。要到组件的原始资源,你需要采取nativeResource属性:

var node = granite.resource.nativeResource.adaptTo(Packages.javax.jcr.Node); 

但是,也应该有一个更快的方法来从资源属性的JS:

val = resource.properties[property]; 

由于这是开发组件属性继承的常见情况,您还可以在实现设计中考虑一些即用型解决方案,如HierarchyNodeInheritanceValueMap APIInheritance Paragraph System (iparsys)

由于这个JS是服务器端与Mozilla Rhino编译,所有这些对象,并在这里使用的方法是Java对象和方法,这样你应该也能以这种方式使用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当前资源的属性值,或者如果为空,则返回父页面上相同位置处资源的属性值,或者如果为空等,则这两行应完成所有魔术。

+0

resource.properties [property];作品!第一个解决方案仍然不起作用。感谢您的其他链接,我不认为我可以使用HierarchyNodeInheritanceValueMap API,因为我使用Javascript HTL使用API​​。 – ltoodee

+0

出于好奇,adaptTo方法再次返回null,或者是不同的错误。这里可能出现的一个可能的错误与获取值的注释行有关,Node API提供了getProperty方法,并且当找不到属性时抛出错误而不是Sling空值。关于HierarchyNodeInheritanceValueMap服务器端JS无论如何都是用Rhino编译成Java,而所使用的所有对象实际上都是Java对象。它也应该能够从不同的包中导入对象,其中一些已经被导入。我用更多的例子更新了我的答案。 –