如何用Ejs、Node和Express在Bootstrap博客模板的多个Article区块渲染文章?
问题排查与解决方案
1. 确认后端数据传递是否正确
首先检查server.js中是否将文章数据正确传入Ejs模板:
- 路由里必须通过
res.render传递文章数组,示例:// server.js let posts = []; // 临时存储,生产环境建议用数据库 app.get('/', (req, res) => { // 若从数据库取数据,需确保查询逻辑正确 res.render('index', { posts: posts }); }); - 如果是前端提交的文章,要确认数据已被后端正确接收并存储到
posts数组(或数据库),渲染页面时能读取到完整数据。
2. 检查Ejs循环语法正确性
确保循环代码无语法错误,正确遍历后端传递的数组:
- 错误示例(常见问题):
<!-- 错误:用for-in遍历数组(会拿到索引而非对象)、变量名不匹配 --> <% for (let post in posts) { %> <article class="blog-post"> <h2><%= post.title %></h2> </article> <% } %> - 正确示例:
或用普通for循环:<!-- 推荐用forEach遍历数组 --> <% posts.forEach(post => { %> <article class="blog-post"> <h2 class="blog-post-title"><%= post.title %></h2> <p class="blog-post-meta"><%= post.date %> by <a href="#"><%= post.author %></a></p> <p><%= post.content %></p> </article> <% }) %><% for (let i = 0; i < posts.length; i++) { %> <article class="blog-post"> <h2><%= posts[i].title %></h2> </article> <% } %>
3. 验证前端提交逻辑
如果是通过表单发布文章,检查前端JS与后端接收逻辑:
- 前端提交代码(确保POST请求正确传参):
const form = document.getElementById('post-form'); form.addEventListener('submit', async (e) => { e.preventDefault(); const postData = { title: document.getElementById('title').value, content: document.getElementById('content').value, author: document.getElementById('author').value }; await fetch('/submit-post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData) }); // 提交后刷新页面重新渲染 window.location.href = '/'; }); - 后端接收代码:
// server.js app.use(express.json()); app.post('/submit-post', (req, res) => { const newPost = { ...req.body, date: new Date().toLocaleDateString() }; posts.push(newPost); res.redirect('/'); });
4. 排查模板继承问题
如果使用了Ejs模板继承(如header.ejs、footer.ejs),确保循环代码放在正确的区块:
- 主模板
layout.ejs需定义内容区块:<body> <% include ./partials/header %> <main class="container"> <%- body %> <!-- 子模板填充的内容区域 --> </main> <% include ./partials/footer %> </body> - 子模板
index.ejs要将循环代码放在body对应的区域内。
5. 调试技巧
- 在Ejs模板中添加调试代码,确认数据是否存在:
<% console.log(posts) %> <!-- 查看终端输出的数据结构 --> <% if (!posts || posts.length === 0) { %> <p>暂无发布的文章</p> <% } else { %> <!-- 循环渲染代码 --> <% posts.forEach(post => { %> <article class="blog-post">...</article> <% }) %> <% } %> - 检查浏览器控制台是否有JS错误,后端终端是否有报错信息。
内容的提问来源于stack exchange,提问作者UltimateKaycee
相关产品推荐
相关产品推荐

