如何在EJS模板中遍历嵌套对象并列出所有图片URL?
在EJS中遍历嵌套字典并输出所有图片URL
嘿,我来帮你搞定这个EJS遍历的问题!首先得先明确你的JSON结构大概是啥样的——假设你传入EJS的数据是类似这样的嵌套字典(每个键对应一个图片对象):
{ "gallery": { "sunset": { "url": "/assets/images/sunset.jpg", "caption": "海边日落" }, "mountain": { "url": "/assets/images/mountain.jpg", "caption": "雪山远景" }, "forest": { "url": "/assets/images/forest.jpg", "caption": "林间小径" } } }
下面给你两种常用的遍历方式,按需选择:
方法1:用Object.values()直接获取图片对象数组
这种方法最简洁,适合只需要图片内容、不需要键名的场景:
<!-- 假设你传给EJS的变量名叫 photoGallery --> <h3>所有图片URL:</h3> <ul> <% Object.values(photoGallery.gallery).forEach(photo => { %> <li> <!-- 输出图片标签 --> <img src="<%= photo.url %>" alt="<%= photo.caption || '未命名图片' %>"> <!-- 或者只输出纯文本URL --> <span>URL:<%= photo.url %></span> </li> <% }) %> </ul>
方法2:用for...in遍历键名(需要键名时用)
如果你需要用到每个图片对应的键名(比如上面的sunset、mountain),可以用这种方式:
<h3>带键名的图片列表:</h3> <% for (const photoKey in photoGallery.gallery) { %> <!-- 可选:过滤掉原型链上的属性,避免意外值 --> <% if (photoGallery.gallery.hasOwnProperty(photoKey)) { %> <div class="photo-item"> <h4>图片:<%= photoKey %></h4> <img src="<%= photoGallery.gallery[photoKey].url %>" alt="<%= photoGallery.gallery[photoKey].caption %>"> <p>URL:<%= photoGallery.gallery[photoKey].url %></p> </div> <% } %> <% } %>
小提示
如果你的JSON结构和示例略有不同(比如图片直接在顶层对象,而不是嵌套在gallery里),只需要调整遍历的路径就行——比如把photoGallery.gallery换成你实际的变量名和层级。
内容的提问来源于stack exchange,提问作者Ryan Hubbard
相关产品推荐
相关产品推荐

