【问题标题】:Repeatedly Render Dust.js Template with New Data使用新数据重复渲染 Dust.js 模板
【发布时间】:2014-05-13 20:08:03
【问题描述】:

什么是重复渲染灰尘模板的最佳方法,同时让它在数据文件中前进它的引用,而不是每次都从头开始重复。例如:

假设我有一个 100 多人的列表,以 JSON 格式存储在一个名为 data 的变量中:

{
    "people": [
        {
            "name": "Jerry",
            "age": "17"
        },
        {
            "name": "Darcy",
            "age": "19"
        },
        {
            "name": "Jacob",
            "age": "25"
        },
        ... and so on for 100 or so people
    ]
}

我有这个 template.tl 文件,它导出一行三个姓名/年龄:

<div class="row">
    <div>{name} - {age}</div>
    <div>{name} - {age}</div>
    <div>{name} - {age}</div>
</div>

我预编译成 template.js

(function(){dust.register("template.tl",body_0);function body_0(chk,ctx){return chk.write("<div class=\"row\"><div>").reference(ctx.get(["name"], false),ctx,"h").write(" - ").reference(ctx.get(["age"], false),ctx,"h").write("</div><div>").reference(ctx.get(["name"], false),ctx,"h").write(" - ").reference(ctx.get(["age"], false),ctx,"h").write("</div><div>").reference(ctx.get(["name"], false),ctx,"h").write(" - ").reference(ctx.get(["age"], false),ctx,"h").write("</div></div>");}return body_0;})();

然后我有一个 index.html 文件,看起来像:

<html>
    <head>
    ...
    </head>

    <body>
        <div id="people"></div>

        <button id="load-more" type="button">Load More</button>
    </body>

    <script src="js/dust-core.min.js"></script>
    <script src="js/template.js"></script>
</html>

最好的方法是什么,所以每次单击按钮时,都会在&lt;div id="people"&gt;&lt;/div&gt; 中附加一行三个人,然后每次单击都会加载接下来的三个人/测试结束数据数组(可以假设人数总是三的倍数以满足我的需要)。

【问题讨论】:

    标签: jquery linkedin dust.js client-side-templating


    【解决方案1】:

    template.tl 更改为:

    <div class="row">
        {#.}
            <div>{.name} - {.age}</div>
        {/.}
    </div>
    

    更改模板有两个好处:

    • 您可以传入任意数量的 people 对象,而不仅仅是 3 个。
    • 如果数组中只剩下 2 个元素,它仍然会正确呈现。

    执行渲染的JavaScript:

    $('#load-more').on('click', function(){
        var next3 = data.people.splice(0, 3);
    
        if(next3.length == 0){
            return; // Array is empty
        }
    
        dust.render('template.tl', next3, function(err, str){
            if(str){
                $('#people').append(str);
            }
        });
    });
    

    最重要的部分是data.people.splice(0, 3),这会从数组中删除 3 个元素并返回它们 - 请参阅 Array.prototype.splice()

    其余的代码只是添加事件监听器并插入渲染模板的 JQuery。

    JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2018-10-01
      相关资源
      最近更新 更多