Domanda

Is there a way of displaying the last entry of a list with Mustache?

I know it is possible to display an array element by it's index described in this answer:

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

I tried (not that I thought it would work):

{{a.a.length.someVariable}}

Is there something like this in Mustache?

È stato utile?

Soluzione

I thought of the following workaround: adding a function to the original object that grabs the last element of the original array.

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 );

And the template:

<div id="target">Loading...</div>
<script id="the-stooges" type="x-tmpl-mustache">
    {{last_stooge}}
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top