能否在Pug的script标签内使用each遍历数组生成JS对象数组?
问题描述
我在单独的projectTemplate.pug文件里定义了这个变量:
- var projectTemplate = [ { full: full250, tiny: tiny250, class: classPhotoset }, { full: full249, tiny: tiny249, class: classPhotoset }, { full: full248, tiny: tiny248, class: classPhotoset }, { full: full247, tiny: tiny247, class: classPhotoset } ]
在script标签外面,我能用each遍历它生成DOM结构:
div each photo in projectTemplate a(class=photo.class)(href=photo.full) img(src=photo.tiny)
想问能不能在script标签里用each遍历这个数组,生成下面格式的availableImgs JavaScript数组:
availableImgs = [ { src : "#{tiny250}", href : '#{full250}', class : '#{classPhotoset}'}, { src : "#{tiny249}", href : '#{full249}', class : '#{classPhotoset}'}, { src : "#{tiny248}", href : '#{full248}', class : '#{classPhotoset}'}, { src : "#{tiny247}", href : '#{full247}', class : '#{classPhotoset}'} ]
解决方案
完全可以实现,但要注意Pug对script标签的解析规则:带.的script.会直接输出纯文本,不会解析Pug的模板语法;不带.的script标签则能正常使用循环、插值这些功能。
给两种可行写法:
写法一:用Pug的each循环生成数组元素
script availableImgs = [ each photo, idx in projectTemplate { src: "#{photo.tiny}", href: "#{photo.full}", class: "#{photo.class}" }#{idx < projectTemplate.length - 1 ? ',' : ''} ]
这里要手动处理数组元素末尾的逗号,避免生成无效的JS代码。
写法二:用JSON.stringify和插值直接生成(更简洁)
script. availableImgs = !{JSON.stringify(projectTemplate.map(photo => ({ src: photo.tiny, href: photo.full, class: photo.class })))}
这种方式借助Pug的!{}插值直接输出处理好的JSON字符串,不用手动管理循环和逗号,效率更高也不容易出错。
另外注意:你示例里的#{src=tiny250}写法不对,正确的插值格式是#{变量名},比如#{photo.tiny}。
内容的提问来源于stack exchange,提问作者dhpro100
相关产品推荐
相关产品推荐

