2017-08-04 72 views
0

我有一個需要共享的頁腳元素。我的計劃是在父/主頁上設置頁腳,但允許子頁面覆蓋這些屬性。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

回答

1

假設你正在使用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對象。它也應該能夠從不同的包中導入對象,其中一些已經被導入。我用更多的例子更新了我的答案。 –