Search code examples
javascripthtmltemplatescouchdbmustache

Get attachments list in CouchDB using Mustaches.js


How to get list of attachments in CouchDB, using Mustaches.js

JSON example:

{
   "_id": "t",
   "_rev": "9-5eed240a008b0eb6efbaf9a439c43279",
   "_attachments": {
       "Doc1.pdf": {
           "content_type": "application/pdf",
           "revpos": 8,
           "digest": "md5-pxnGZT6uqX4n2+vNNIOs/g==",
           "length": 200633,
           "stub": true
       },
       "Doc2.pdf": {
           "content_type": "application/pdf",
           "revpos": 6,
           "digest": "md5-fxnGZT6uqX2n2+vNNI41s/g==",
           "length": 100333,
           "stub": true
       }
   }
}

My template looks like this:

{{^isAttEmpty}}
  <p>Lista załączników:<p>
   <ul>
    {{#_attachments}}
     <li>{{@key}} - URL:{{This will be URL to Image}}</li>
    {{/_attachments}}
   </ul>
 {{/isAttEmpty}}

Did Mustache.js have build in function to iterate objects ? Or should I parsing to array before send to Mustaches ?


Solution

  • As far as I know, Mustache.js can iterate only over array members, not object keys.

    In your show function you will have to format the object you will send to Mustache accordingly. Here is a function you could use to transform attachments into an array:

    function formatAttachments(attachments, docID) {
      var result = [];
      for (a in attachments) {
        result.push({
          name: a,
          size: Math.round(attachments[a].length/104857.6)/10,
          url: docID + "/" + a
        });
      }
      return result;
    }