要限制组件只能在特定模板中使用,可以使用AEM 6.1中的模板编辑框架(Template Editor Framework)来实现。
以下是一种解决方法的代码示例:
import com.adobe.granite.ui.components.TemplateEditorHook;
import com.adobe.granite.ui.components.ds.AbstractDataSource;
import com.adobe.granite.ui.components.ds.DataSource;
import com.adobe.granite.ui.components.ds.SimpleDataSource;
import com.adobe.granite.ui.components.ds.ValueMapResource;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Component(service = TemplateEditorHook.class)
public class TemplateEditorHookImpl implements TemplateEditorHook {
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Override
public DataSource getComponentDataSource(SlingHttpServletRequest request) {
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
Resource templatesRoot = resourceResolver.getResource("/conf/global/settings/wcm/templates");
List templatePaths = getTemplatePaths(templatesRoot);
return new SimpleDataSource(new AbstractDataSource.EntryIterator() {
@Override
protected Iterator getResources() {
List resources = new ArrayList<>();
for (String templatePath : templatePaths) {
Resource template = resourceResolver.getResource(templatePath);
if (template != null) {
resources.add(template);
}
}
return resources.iterator();
}
@Override
protected Object computeValue(Resource resource) {
String templatePath = resource.getPath();
String templateTitle = resource.getValueMap().get("jcr:title", String.class);
return new ValueMapResource(resource, templatePath, templateTitle);
}
});
} catch (Exception e) {
// Handle exception
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
return null;
}
private List getTemplatePaths(Resource resource) throws RepositoryException {
List templatePaths = new ArrayList<>();
Node node = resource.adaptTo(Node.class);
if (node != null) {
Node[] children = node.getNodes();
for (Node child : children) {
if (child.hasProperty("sling:resourceType")) {
String resourceType = child.getProperty("sling:resourceType").getString();
if (resourceType.equals("wcm/core/components/page")) {
templatePaths.add(child.getPath());
}
}
}
}
return templatePaths;
}
}
service.pid = com.example.TemplateEditorHookImpl
通过以上步骤,你可以在AEM 6.1中实现限制组件只能在特定模板中使用的功能。