bucle condicional en mustache.js

How can I output <hr> after every iteration except last one with mustache.js. I tried javascript for loop but I couldn't get rid of last <hr>. (Some people suggest using handlebars.js but I would like stay with mustache.)

Here is my json (the list gets bigger as more employees get added)

    {
      employees: [
        {firstName: "John", lastName: "Smith"},
        {firstName: "John", lastName: "Doe"},
        {firstName: "Jane", lastName: "Doe"}    
       ]
    }

I want this html output:

John Smith
<hr>
John Doe
<hr>
Jane Doe

preguntado el 01 de febrero de 12 a las 01:02

2 Respuestas

En cuanto al Mustache Manual, you'll want to use what's referred to as "Inverted Sections". From the manual:

An inverted section begins with a caret (hat) and ends with a slash. That is {{^person}} begins a "person" inverted section while {{/person}} ends it.

While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn't exist, is false, or is an empty list.

To utilize this, you could add an extra attribute to the last employee to distinguish it.

JSON:

{
  "employees": [
    {"firstName": "John", "lastName": "Smith"},
    {"firstName": "John", "lastName": "Doe"},
    {"firstName": "Jane", "lastName": "Doe", "last": true}    
   ]
}

Mustache Template:

{{#employees}}
  {{firstName}} {{lastName}}
  {{^last}}
    <hr />
  {{/last}}
{{/employees}}

This is very similar to what the Mustache Demo showcases, using the "first" attribute on the first object in the array of colors.

Respondido 01 Feb 12, 05:02

Si el propósito de <hr/> is purely for style, why not use a CSS selector like :not(:last-child)?

JavaScript:

var tpl = "<ul>{{#employees}}<li>{{firstName}} {{lastName}}</li>{{/employees}}</ul>",
        data = {
  "employees": [
    {"firstName": "John", "lastName": "Smith"},
    {"firstName": "John", "lastName": "Doe"},
    {"firstName": "Jane", "lastName": "Doe", "last": true}    
   ]
},
    html = Mustache.to_html(tpl, data);

document.write(html);

CSS:

li:not(:last-child) {
    border-bottom: 1px solid blue;
}

Here's a working jsFiddle to see it in action

Respondido 01 Feb 12, 11:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.