使用 JavaScript Use-Api 我能够创建一个自定义对象并将其返回到一个 html 文件。此功能允许我创建自定义对象列表,可用于创建菜单或其他复杂的类似列表的组件。
假设我有以下内容结构:
/content
/project
/homepage
/contentpage1
/contentpage1.1
/contentpage1.2
/contentpage1.3 (hidden)
/contentpage2
/contentpage1.1 (hidden)
/contentpage1.2 (hidden)
/contentpage1.3 (hidden)
/contentpage3
/contentpage4
菜单应仅包含第一级内容页。每个菜单项都应该有带有二级内容页面的下拉列表,如果它们存在并且没有隐藏的话。我可以使用以下代码在 JavaScript 中执行此操作:
"use strict";
use(function() {
function getMenuItems() {
var currentPageDepth = currentPage.getDepth();
var menuObjects = [];
if(currentPageDepth >= 3) {
var homePage = currentPage.getAbsoluteParent(2);
var list = homePage.listChildren();
while(list.hasNext()) {
var tempPage = list.next()
var customPageObject = createMenuItemObject(tempPage);
menuObjects.push(customPageObject);
}
}
return menuObjects;
}
function createMenuItemObject(page) {
// ...
// looking for any other properties of page or its children
// ...
return {page: page,
visibleChildrenExists: visibleChildrenExists(page)};
}
function visibleChildrenExists(page) {
var list = page.listChildren();
var visibleChildrenExists = false;
while(list.hasNext()) {
var subPage = list.next();
if(!subPage.isHideInNav()) {
visibleChildrenExists = true;
break;
}
}
return visibleChildrenExists;
}
return {
menuObjectsList: getMenuItems(),
};
}
HTML:
<headerComponent data-sly-use.headerComponentJS="headerComponent.js" data-sly-unwrap />
<menuItems data-sly-list.menuItem="${headerComponentJS.menuObjectsList}" data-sly-unwrap >
<li class='${menuItem.visibleChildrenExists ? "" : "direct"}' data-sly-test="${!menuItem.page.hideInNav}">
<a href="${menuItem.page.path}.html">${menuItem.page.title}</a>
<ul data-sly-test="${menuItem.visibleChildrenExists}" data-sly-list.submenuItem="${menuItem.page.listChildren}">
<li data-sly-test="${!submenuItem.hideInNav}">
<a href="${submenuItem.path}.html">${submenuItem.title}</a>
</li>
</ul>
</li>
</menuItems>
为什么要使用 Java Use-Api?在 Resource 或 Node 等接口上操作更容易。看起来它在 JavaScript 中不能很好地工作,但我需要有可能返回具有多个属性的自定义对象。
The question is: is it even possible to do something similar using Java Use-Api? What do I have to return? I can't return a map, because it won't be possible to access its elements since it's not possible to pass a parameter to Java Use-Api method... Any suggestion?