You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sightly表格分页实现求助:JavaScript新手开发遇阻

为Sightly子页面列表表格实现分页功能

针对你用Sightly展示子页面列表的需求,分页需要结合后端数据截取和前端动态渲染来实现,以下是分步实现方案:


1. 后端处理分页数据(Java Use API)

首先需要在AEM中通过Use类来处理子页面的分页逻辑,控制每页显示数量,并根据请求参数返回对应页码的子页面。

编写PaginationHelper Use类

package com.example;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Model(adaptables = SlingHttpServletRequest.class)
public class PaginationHelper {
    @SlingObject
    private SlingHttpServletRequest request;
    
    @SlingObject
    private Resource currentPage;
    
    private List<Resource> paginatedChildren;
    private int currentPageNum;
    private int totalPages;
    private final int PAGE_SIZE = 10; // 可自定义每页显示条数

    @PostConstruct
    protected void init() {
        // 获取当前页码,默认1
        currentPageNum = Integer.parseInt(request.getParameterOrDefault("page", "1"));
        // 获取当前页面的所有子页面
        List<Resource> allChildren = currentPage.getChildren().stream().collect(Collectors.toList());
        int totalItems = allChildren.size();
        
        // 计算总页数
        totalPages = (int) Math.ceil((double) totalItems / PAGE_SIZE);
        
        // 处理页码边界,防止越界
        if (currentPageNum < 1) currentPageNum = 1;
        if (currentPageNum > totalPages) currentPageNum = totalPages;
        
        // 截取当前页的子页面数据
        int startIndex = (currentPageNum - 1) * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, totalItems);
        paginatedChildren = allChildren.subList(startIndex, endIndex);
    }

    // Getter方法供Sightly调用
    public List<Resource> getPaginatedChildren() { return paginatedChildren; }
    public int getCurrentPageNum() { return currentPageNum; }
    public int getTotalPages() { return totalPages; }
    public boolean hasPrevious() { return currentPageNum > 1; }
    public boolean hasNext() { return currentPageNum < totalPages; }
}

2. 修改Sightly代码,绑定分页数据

更新表格主体(tbody)

将原来直接遍历所有子页面的代码,改为遍历分页后的子页面:

<sly data-sly-use.pagination="com.example.PaginationHelper" />

<tbody id="body">
  <tr class="ninja_table_row_0 nt_row_id_157" data-sly-repeat.child="${pagination.paginatedChildren}">
    <td class="ninja_column_0 ninja_clmn_nm_logoname footable-first-visible" style="display: table-cell;">
      <a href="${child.getProperties['path']}.html">
        <img src="${child.getProperties['logo']}" alt="${child.getProperties['company']}">
      </a>
    </td>
    <td class="ninja_column_1 ninja_clmn_nm_company" style="display: table-cell;">
      <a href="${child.getProperties['path']}.html">${child.getProperties['company']} </a>
    </td>
    <td class="ninja_column_2 ninja_clmn_nm_boothno" style="display: table-cell;">${child.getProperties['boothNo']}</td>
    <td class="ninja_column_3 ninja_clmn_nm_country" style="display: table-cell;">${child.getProperties['country']}</td>
    <td class="ninja_column_4 ninja_clmn_nm_profile footable-last-visible" style="display: table-cell;">${child.getProperties['profile']}</td>
  </tr>
</tbody>

动态渲染分页控件(tfoot)

把静态的页码按钮改成根据后端数据动态生成,同时处理禁用状态和跳转链接:

<tfoot>
  <tr class="footable-paging">
    <td colspan="5">
      <div class="footable-pagination-wrapper">
        <ul class="pagination" id="demo">
          <!-- 首页按钮 -->
          <li class="footable-page-nav ${!pagination.hasPrevious ? 'disabled' : ''}" data-page="first" aria-label="first page">
            <a class="footable-page-link" href="${request.requestURL.toString}${request.requestURL.toString.contains('?') ? '&' : '?'}page=1">«</a>
          </li>
          <!-- 上一页按钮 -->
          <li class="footable-page-nav ${!pagination.hasPrevious ? 'disabled' : ''}" data-page="prev" aria-label="previous" id="prev-page">
            <a class="footable-page-link" href="${request.requestURL.toString}${request.requestURL.toString.contains('?') ? '&' : '?'}page=${pagination.currentPageNum - 1}">‹</a>
          </li>
          <!-- 动态生成页码按钮 -->
          <sly data-sly-repeat.pageNum="${1..pagination.totalPages}">
            <li class="footable-page visible ${pagination.currentPageNum == pageNum ? 'active' : ''}" data-page="${pageNum}" aria-label="page ${pageNum}">
              <a class="footable-page-link" href="${request.requestURL.toString}${request.requestURL.toString.contains('?') ? '&' : '?'}page=${pageNum}">${pageNum}</a>
            </li>
          </sly>
          <!-- 下一页按钮 -->
          <li class="footable-page-nav ${!pagination.hasNext ? 'disabled' : ''}" data-page="next" aria-label="next" id="next-page">
            <a class="footable-page-link" href="${request.requestURL.toString}${request.requestURL.toString.contains('?') ? '&' : '?'}page=${pagination.currentPageNum + 1}">›</a>
          </li>
          <!-- 末页按钮 -->
          <li class="footable-page-nav ${!pagination.hasNext ? 'disabled' : ''}" data-page="last" aria-label="last page">
            <a class="footable-page-link" href="${request.requestURL.toString}${request.requestURL.toString.contains('?') ? '&' : '?'}page=${pagination.totalPages}">»</a>
          </li>
        </ul>
        <div class="divider"></div>
        <span class="label label-default">第 ${pagination.currentPageNum} 页 / 共 ${pagination.totalPages} 页</span>
      </div>
    </td>
  </tr>
</tfoot>

3. 可选:实现无刷新分页(AJAX)

如果需要页面不刷新切换页码,可以添加以下JavaScript代码:

document.addEventListener('DOMContentLoaded', function() {
  bindPaginationEvents();

  function bindPaginationEvents() {
    const paginationLinks = document.querySelectorAll('.footable-page-link');
    const tableBody = document.getElementById('body');
    const paginationWrapper = document.querySelector('.footable-pagination-wrapper');

    paginationLinks.forEach(link => {
      link.addEventListener('click', function(e) {
        e.preventDefault();
        const pageUrl = this.getAttribute('href');

        fetch(pageUrl)
          .then(res => res.text())
          .then(html => {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html;
            
            // 更新表格内容和分页控件
            tableBody.innerHTML = tempDiv.querySelector('#body').innerHTML;
            paginationWrapper.innerHTML = tempDiv.querySelector('.footable-pagination-wrapper').innerHTML;
            
            // 重新绑定事件(因为分页控件被替换)
            bindPaginationEvents();
          })
          .catch(err => console.error('分页请求失败:', err));
      });
    });
  }
});

核心注意事项

  • 优先使用后端分页:避免一次性加载所有子页面,数据量大时会严重影响性能
  • 处理页码边界:确保当前页码始终在1到总页数之间,防止数组越界错误
  • 保留URL状态:通过page参数传递页码,页面刷新后仍能保持当前页
  • 继承原有样式:保留footable相关类,保证分页控件的样式正常显示

内容的提问来源于stack exchange,提问作者Janhavi Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:06:09