【问题标题】:Access the last entry of a list with Mustache使用 Mustache 访问列表的最后一个条目
【发布时间】:2014-04-16 11:55:00
【问题描述】:

有没有办法用 Mustache 显示列表的最后一个条目?

我知道可以通过this answer 中描述的索引来显示数组元素:

// use first element of array a
{{a.0}}

我试过了(不是我认为它会起作用):

{{a.a.length.someVariable}}

Mustache 中有这样的东西吗?

【问题讨论】:

    标签: javascript mustache templating


    【解决方案1】:

    我想到了以下解决方法:向原始对象添加一个函数,该函数抓取原始数组的最后一个元素。

    var template = $('#the-stooges').html();
    Mustache.parse( template );
    var init_array = {
      "stooges": [
        { "name": "Moe" },
        { "name": "Larry" },
        { "name": "Curly" }
      ]
    };
    
    var func_var = {
        "last_stooge": function () {
            var last = this.stooges.length - 1;
            return this.stooges[last].name;
          }
    };
    
    $.extend( init_array, func_var ); // http://stackoverflow.com/a/10384883/1287812
    var rendered = Mustache.render( template, init_array );
    $('#target').html( rendered );
    

    还有模板:

    <div id="target">Loading...</div>
    <script id="the-stooges" type="x-tmpl-mustache">
        {{last_stooge}}
    </script>
    

    【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多