Cómo iterar sobre la matriz de objetos en Manillar?


Esto puede parecer una pregunta tonta, pero no puedo encontrar la respuesta en ninguna parte.

Estoy golpeando esta Api Web que devuelve una matriz de objetos en formato JSON:

matriz de objetos

Handlebars docs muestra el siguiente ejemplo:

<ul class="people_list">
  {{#each people}}
  <li>{{this}}</li>
  {{/each}}
</ul>

En el contexto de:

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

En mi caso no tengo un nombre para la matriz, es solo el objeto raíz de la respuesta. He intentado usar {{#each}} sin suerte.

Primera vez usando manillares... ¿qué soy ¿desaparecido?

UPDATE

Aquí hay un violín simplificado para mostrar lo que estoy pidiendo: http://jsfiddle.net/KPCh4/2 /

¿handlebars requiere que la variable de contexto sea un objeto y no una matriz?

Author: emzero, 2014-03-27

5 answers

Puede pasar this a cada bloque. Ver aquí: http://jsfiddle.net/yR7TZ/1/

{{#each this}}
    <div class="row"></div>
{{/each}}
 116
Author: AZ.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:30:34

Este violín tiene each y json directo. http://jsfiddle.net/streethawk707/a9ssja22/.

A continuación se presentan las dos formas de iterar sobre matriz. Uno es con el paso json directo y otro es nombrar la matriz json mientras se pasa al titular de contenido.

Eg1: El siguiente ejemplo está llamando directamente a la clave json (data) dentro de la variable small_data.

En html use el siguiente código:

<div id="small-content-placeholder"></div>

Lo siguiente se puede colocar en encabezado o cuerpo de html:

<script id="small-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#data}}
                <tr>
                    <td>{{username}}
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/data}}
        </tbody>
    </table>
</script>

El siguiente documento está listo:

var small_source   = $("#small-template").html();
var small_template = Handlebars.compile(small_source);

El siguiente es el json:

var small_data = {
            data: [
                {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
            ]
        };

Finalmente adjunte el json al titular del contenido:

$("#small-content-placeholder").html(small_template(small_data));

Eg2: Iteración usando cada uno.

Considere el siguiente json.

var big_data = [
            {
                name: "users1",
                details: [
                    {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            },
            {
                name: "users2",
                details: [
                    {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            }
      ];

Al pasar el json al titular del contenido, simplemente nómbralo de esta manera:

$("#big-content-placeholder").html(big_template({big_data:big_data}));

Y la plantilla se ve como:

<script id="big-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#each big_data}}
                <tr>
                    <td>{{name}}
                            <ul>
                                {{#details}}
                                    <li>{{username}}</li>
                                    <li>{{email}}</li>
                                {{/details}}
                            </ul>
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>
 9
Author: street hawk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:30:07

Quise decir en la llamada template()..

Solo necesita pasar los resultados como un objeto. Así que en lugar de llamar

var html = template(data);

Do

var html = template({apidata: data});

Y use {{#each apidata}} en su código de plantilla

Demo en http://jsfiddle.net/KPCh4/4 /
(eliminado algunos restos de if código que se estrelló )

 8
Author: Gabriele Petrioli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:30:48

Handlebars puede usar un array como contexto. Puede usar . como la raíz de los datos. Así que puede recorrer los datos de su matriz con {{#each .}}.

var data = [
  {
    Category: "General",
    DocumentList: [
      {
        DocumentName: "Document Name 1 - General",
        DocumentLocation: "Document Location 1 - General"
      },
      {
        DocumentName: "Document Name 2 - General",
        DocumentLocation: "Document Location 2 - General"
      }
    ]
  },
  {
    Category: "Unit Documents",
    DocumentList: [
      {
        DocumentName: "Document Name 1 - Unit Documents",
        DocumentList: "Document Location 1 - Unit Documents"
      }
    ]
  },
  {
    Category: "Minutes"
  }
];

$(function() {
  var source = $("#document-template").html();
  var template = Handlebars.compile(source);
  var html = template(data);
  $('#DocumentResults').html(html);
});
.row {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="DocumentResults">pos</div>
<script id="document-template" type="text/x-handlebars-template">
  <div>
  {{#each .}}
    <div class="row">
      <div class="col-md-12">
        <h2>{{Category}}</h2>
        {{#DocumentList}}
        <p>{{DocumentName}} at {{DocumentLocation}}</p>
        {{/DocumentList}}
      </div>
    </div>
  {{/each}}
  </div>
</script>
 3
Author: Emre Efendi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:31:39

Usando this y {{this}}. Consulte el código a continuación en el nodo.js:

var Handlebars= require("handlebars");
var randomList= ["James Bond", "Dr. No", "Octopussy", "Goldeneye"];
var source= "<ul>{{#each this}}<li>{{this}}</li>{{/each}}</ul>";
var template= Handlebars.compile(source);
console.log(template(randomList));

Salida de registro de consola:

<ul><li>James Bond</li><li>Dr. No</li><li>Octopussy</li><li>Goldeneye</li></ul>
 1
Author: Megatron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:32:08