【问题标题】:Dust - Looping through json dataDust - 循环通过 json 数据
【发布时间】:2014-06-13 11:18:25
【问题描述】:

我非常卡在这里。我使用灰尘作为模板编译器,但无论出于何种原因,我只从我的 json 中返回一个值,它并没有循环并返回所有内容。所以我得到的只是“DWade”关于发生了什么的任何想法?灰尘新手,所以代码示例真的很有帮助。

JSON:

{
 "locations": [
 {
  "userName": "MKelly",
  "hours":"9-5"
 },
 {
  "userName": "MReynolds",
  "hours":"10-2"
 },
 {
  "userName": "DWade",
  "hours":"9-9"
 }
 ]
}

这是我的 jQuery:

var compiled = dust.compile($('.dust-info').html(), "tmp_skill");
dust.loadSource(compiled);

    $.getJSON("/services/userInfo?" + userTypes, function(data) {      
      $.each( data.locations, function( key, val ) {
      dust.render("tmp_skill", val, function(err, out) {
      //HTML output
      $('.dust-info').html(out);
      });
    });

模板:

<div class="dust-info">
   {userName}
   {hours}
 </div>

【问题讨论】:

    标签: jquery json dust.js


    【解决方案1】:

    我以前从未真正使用过灰尘,但希望我能帮上一点忙。

    首先,您通过每次通过$.each 时更改 .dust-info 的 innerHTML 来清除 .dust-info 中的所有内容

    试试这个作为模板

    {#locations}
        <div class="dust-info">
            {userName} {hours}
        </div>
    {:else}
        No Location
    {/locations}
    

    在这里试试http://akdubya.github.io/dustjs/ - 将模板粘贴到 1 中,将您的模板数据粘贴到 3 中。

    别忘了你需要先编译你的模板才能使用它。

    之后你应该可以做到这一点

    dust.render("tmp_skill", data.locations, function(err, out) {
        //append generated output to body
        $(body).append(out);
    })
    

    此示例只是将输出附加到正文

    【讨论】:

    • 谢谢,您发送的内容似乎有效,但我的代码有什么问题?当我尝试将其添加到我的时,我仍然只得到一个结果。
    • 太棒了!非常感谢!
    【解决方案2】:

    作为上面带有 andyw 的 cmets,您得到 1 个结果,因为在 javascript 代码中,您使用了这个:$('.dust-info').html(out); 使用 .html(out): js 将找到带有“dust-info”类的标签,然后使用 data.locations 循环并仍然替换此标签的 html,而不是附加 - 或显示为列表,这就是为什么你只看到 1 个结果. andyw 的回答是在灰尘模板中循环数据和显示数据列表的最佳方式。

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2012-09-16
      相关资源
      最近更新 更多