如何在Handlebars(HBS)中逐行展示MongoDB中的Ingredients数组?
解决Ingredients数组逐行展示的问题
你的核心问题是在Handlebars模板里遍历错了对象——你现在用{{#each recipe}}遍历的是单个Recipe文档,而不是文档里的ingredients数组。我们需要调整模板的遍历逻辑,同时还要确认提交表单的参数是否正确传递数组。
1. 修改recipe.hbs模板
把遍历的目标改成recipe.ingredients,这样就能逐个渲染数组里的每一项:
<div class="row pt-4"> <div class="col-12"> <h4>Ingredients</h4> <ul class="list-group list-group-flush"> {{#each recipe.ingredients}} <li class="list-group-item">{{this}}</li> {{/each}} </ul> </div> </div>
说明:
{{#each recipe.ingredients}}:明确遍历Recipe文档中的ingredients数组{{this}}:指代当前遍历到的数组元素(也就是单条食材内容)- 若需要保留食材文本的换行格式,可以把
<li>的样式改回style="white-space: pre-line"
2. 修复提交表单的数组传递问题
你的submit-recipe.hbs里,input的name是ingredients,这会导致提交多个食材时,后端只会收到最后一个输入的值。需要把name改成ingredients[],这样Express才能正确解析成数组:
<div class="col-12"> <label for="name" class="form-label">Ingredients</label><br> <small>Example: Ice</small> <div class="ingredientList"> <div class="ingredeintDiv mb-1"> <input type="text" name="ingredients[]" class="form-control"> </div> </div> </div>
补充提示:
如果你的前端是通过JS动态添加更多食材输入框的,确保每个新增的input的name都设置为ingredients[],这样后端才能正确接收完整的食材数组。
3. 确认后端存储逻辑(可选)
如果你的创建Recipe接口还没适配数组接收,确保直接把req.body.ingredients存入数据库即可——因为Mongoose Schema里已经定义ingredients为Array类型,只要后端收到数组就能正确存储。示例创建接口如下:
exports.createRecipe = async(req, res) => { try { const newRecipe = new Recipe({ name: req.body.name, description: req.body.description, email: req.body.email, ingredients: req.body.ingredients, // 直接存入数组 category: req.body.category, image: req.body.image }); await newRecipe.save(); res.redirect('/'); } catch (error) { res.status(500).send({message: error.message || "Error Occured" }); } }
完成以上修改后,你的食材数组就能在recipe页面逐行显示在列表中了。
内容的提问来源于stack exchange,提问作者Harshad.N
相关产品推荐
相关产品推荐

