采用ejs制作一个具有分页功能的表格组件,表格数据从Web服务器获取。
时间: 2023-11-22 22:51:42 浏览: 31
好的,下面是一个基于ejs和Node.js的具有分页功能的表格组件示例:
首先,我们需要创建一个包含表格模板和分页模板的ejs文件,例如:
```
<!-- table.ejs -->
<table>
<thead>
<tr>
<% headers.forEach(function(header) { %>
<th><%= header %></th>
<% }); %>
</tr>
</thead>
<tbody>
<% data.forEach(function(row) { %>
<tr>
<% row.forEach(function(cell) { %>
<td><%= cell %></td>
<% }); %>
</tr>
<% }); %>
</tbody>
</table>
<!-- pagination.ejs -->
<ul class="pagination">
<% if (currentPage > 1) { %>
<li><a href="?page=<%= currentPage - 1 %>">«</a></li>
<% } %>
<% for (var i = 1; i <= pageCount; i++) { %>
<% if (i === currentPage) { %>
<li class="active"><a href="?page=<%= i %>"><%= i %></a></li>
<% } else { %>
<li><a href="?page=<%= i %>"><%= i %></a></li>
<% } %>
<% } %>
<% if (currentPage < pageCount) { %>
<li><a href="?page=<%= currentPage + 1 %>">»</a></li>
<% } %>
</ul>
```
然后,我们需要编写一个Node.js服务器端脚本来读取数据和呈现模板,例如:
```
const express = require('express');
const ejs = require('ejs');
const app = express();
// Mock data
const data = [
['John', 'Doe', 'john@example.com'],
['Jane', 'Doe', 'jane@example.com'],
['Bob', 'Smith', 'bob@example.com'],
['Alice', 'Smith', 'alice@example.com'],
['Tom', 'Jones', 'tom@example.com'],
['Mary', 'Jones', 'mary@example.com']
];
// Configure template engine
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
// Render table with pagination
app.get('/', function(req, res) {
const pageSize = 2;
const currentPage = parseInt(req.query.page || '1');
const pageCount = Math.ceil(data.length / pageSize);
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const headers = ['First Name', 'Last Name', 'Email'];
const rows = data.slice(startIndex, endIndex);
res.render('table', { headers: headers, data: rows, pageCount: pageCount, currentPage: currentPage });
});
// Start server
app.listen(3000, function() {
console.log('Server started on port 3000');
});
```
最后,我们可以在浏览器中访问 http://localhost:3000?page=1 来查看呈现的表格和分页。当我们点击分页链接时,服务器会根据请求的页数重新计算数据的起始和结束位置,并呈现新的表格和分页。