mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 635 forks source link

for-loop with array's #1404

Closed johntom closed 1 year ago

johntom commented 2 years ago

Hi

Mustache let's me loop on the following payload1 with this code

   <template id="foo">
    {{#.}} 

        <div class="flex-shrink-0">
         <img class=" img.responsive" src="https://storage.googleapis.com/hwthumbs/tn_{{Filename}}" alt=""> 

        <div class="flex-1 bg-white p-6 flex flex-col justify-between">
          <div class="flex-1">
            <a href="" class="block mt-2" >
              <p class="text-xl font-semibold text-gray-900">{{Title}}</p>
              <p class="mt-3 text-base text-gray-500">{{Medium}}</p>
            </a>
          </div>
          <div class="mt-6 flex items-center">

          </div>
        </div>
      </div>
     {{/.}}
   </div>

  </template>

if my paload looks like payload2 nunjucks works fine. How do I loop with payload1 where the array does not have data object? ...

...

payload1 array without object

 [
          {
          _id: "61db7861fd3f2f64a6b1db31",
          Filename: "60.jpg",
          Title: "Glow 1",
          Medium: "Gold leaf, glass, and oil on panel"
          },
          {
          _id: "61db7861fd3f2f64a6b1db32",
          Filename: "61.jpg",
          SortOrder: 61,
          Title: "Glow 2",
          Medium: "Gold leaf, glass, and oil on panel"
          }]

payload2 array with object
data: [
          {
          _id: "61db7861fd3f2f64a6b1db31",
          Filename: "60.jpg",
          Title: "Glow 1",
          Medium: "Gold leaf, glass, and oil on panel"
          },
          {
          _id: "61db7861fd3f2f64a6b1db32",
          Filename: "61.jpg",
          SortOrder: 61,
          Title: "Glow 2",
          Medium: "Gold leaf, glass, and oil on panel"
          }]
johntom commented 1 year ago

i just wrap it wiih an object

var data = JSON.parse(text); var data = { results: data };