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

如何使用Handlebars将MongoDB返回的JSON数组数据逐行显示?

用Handlebars实现MongoDB数组数据的逐行显示

没问题!要把你从MongoDB拿到的description数组里的每一条内容逐行展示,Handlebars的{{#each}}循环就是最直接的解决方案,我给你详细说下怎么做:

1. 确认数据传递正确

首先确保你的后端已经把MongoDB查询到的文档对象(比如命名为emergencyGuide)正确传递给了Handlebars模板,description字段是数组类型,而不是被意外转换成了字符串。

2. 编写Handlebars模板代码

在你的模板里,用{{#each}}遍历description数组,每一项用块级元素(比如<p>或者列表标签)包裹,就能实现逐行显示:

<div class="emergency-guide">
  <h1>{{title}}</h1>
  <!-- 遍历description数组,逐个渲染每一条 -->
  {{#each description}}
    <p>{{this}}</p>
  {{/each}}
</div>

如果你想做成更规范的有序列表,也可以这样写(刚好你的数组项自带序号,或者也可以去掉序号让<ol>自动生成):

<div class="emergency-guide">
  <h1>{{title}}</h1>
  <ol>
    {{#each description}}
      <li>{{this}}</li>
    {{/each}}
  </ol>
</div>

3. 效果说明

上面的模板渲染后,会把description里的每一条内容单独放在一个<p>(或<li>)标签里,因为这些是块级元素,浏览器默认会自动换行,最终呈现出来就是逐行显示的效果,比如:

Asthma

  1. Help the person sit in a comfortable position and help them take their medicine.

  2. Reassure the person.

  3. If the attack becomes severe, they dont have their medication or they dont improve call the emergency services.

小提示

如果发现渲染后所有内容挤在一起,先检查description是不是真的数组类型——有时候后端可能不小心把数组转成了JSON字符串,这时候需要先把它解析回数组再传递给模板哦。

内容的提问来源于stack exchange,提问作者n.fin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:00:24