【问题标题】:Dust iterate over array灰尘迭代数组
【发布时间】:2018-06-21 06:46:23
【问题描述】:

我正在使用 Kraken.js、灰尘、猫鼬。我有以下使用 mongoose 从 MongoDB 获得的对象。

artist = {
    "_id" : ObjectId("xxxxxxxx"),
    "first_name" : "myName",
    "last_name" : "myLastname",
    "description" : "Sample Description here",
    "thumbnail" : "thumbnail.jpg",
    "works" : [ 
        "art1.jpg", 
        "art2.jpg"
    ]
}

我发送到我的模板的整个模型的名称是艺术家(单数)。

我想为works的每个成员生成image标签。

<img src="art1.jpg" />
<img src="art2.jpg" />

我尝试过关注 sn-ps,但它不起作用

{#.}
    <img src="./../../images/artists/{.works}" alt="" />
{/.}

{#artist.works}
    <img src="./../../images/artists/{.works}" alt="" />
{/.artist.works}

它会打印“”

非常感谢您的帮助

【问题讨论】:

  • 那么是什么阻止了你?
  • 根据tutorial你需要使用sections来循环。
  • artist.works 是一个 Array - 因此您可以对其进行迭代
  • @JaromandaX 你的意思是这样 => ` {#artist.works} {/artist.works}`
  • 假设你比我更了解灰尘

标签: javascript dust.js kraken.js


【解决方案1】:

TL/DR:

  1. 如果传递的上下文是artist 对象,那么您只需要迭代works 对象。
  2. 如果传递的上下文是一个包含artist 对象的对象,那么您需要使用artist.works 进行迭代。

这是您示例的工作版本。

var data = {
  "artist": {
    "first_name": "myName",
    "last_name": "myLastname",
    "description": "Sample Description here",
    "thumbnail": "thumbnail.jpg",
    "works": [
      "art1.jpg",
      "art2.jpg"
    ]
  }
};

var compiled = dust.compile('<ul>{#artist.works}<li><a href="{.}" >{.}</a></li>{/artist.works}</ul>', 'hello');
// Register the template with Dust
dust.loadSource(compiled);
// Render the template
dust.render('hello', data, function(err, out) {
  // `out` contains the rendered output.
  document.getElementById('output').innerHTML = out;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/dustjs-linkedin/2.7.5/dust-full.js"></script>

<div id="output" />

【讨论】:

  • 感谢您的帮助 :) ,结果为 ibb.co/bYSpUd , ibb.co/mK6ipd
  • 第一张图片是我写代码,第二张图片是浏览器中的结果
  • @JamieJamier 好的。由于上下文不是artist对象,所以需要像{#artist.works}&lt;img src="./../../images/artists/{.}" alt="" /&gt;{/artist.works}这样写。
  • 我试过了,但它不起作用,我想出了相同的解决方案,但不知道为什么它不起作用
  • @thefourtheye 答案中的灰尘代码应该可以正常工作;但是,在使用它来渲染灰尘模板之前,您需要将 mongoose 文档更改为 json“模型”。在 mongoose 文档上调用 toJSON 应该会返回一个您可以使用的正确 json 对象。 mongoosejs.com/docs/api.html#document_Document-toJSON
猜你喜欢
  • 2013-12-24
  • 2015-09-27
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多