1

Render attachment names from couchdb without conversion using handlebars or mustache template.

{
   "_id":"123",
   "_attachments":{
      "evil.jpg":{
         "content_type":"image/jpeg",
         "revpos":32,
         "digest":"md5-CKtT5WWRLkmGDD3/DhK6FQ==",
         "length":41915,
         "stub":true
      }
   }
}

I think this is duplicate of Getting key's in handlebar.

// based on the `#each` helper, requires jQuery (for jQuery.extend)
Handlebars.registerHelper('each_hash', function(context, options) {
    var fn = options.fn, inverse = options.inverse;
    var ret = "";

    if(typeof context === "object") {
        for(var key in context) {
            if(context.hasOwnProperty(key)) {
                // clone the context so it's not
                // modified by the template-engine when
                // setting "_key"
                var ctx = jQuery.extend(
                    {"_key":key},
                    context[key]);

                ret = ret + fn(ctx);
            }
        }
    } else {
        ret = inverse(this);
    }
    return ret;
});
Community
  • 1
  • 1
Alex Voikov
  • 121
  • 1
  • 10

1 Answers1

1

The developers of handlebars are discussing putting this in

That helper should do the job anyway if you just want to add it. Your template would be like this.

{{#each_hash _attachments}}
    {{_key}} - {{content_type}}
{{else}}
    You didn't pass in an object!
{{/each_hash}}

The helper essentially just iterates through the object and does the conversion on the fly. It iterates through the object and adds the key as the _key variable. You don't have to include the else statement and it will return nothing by default.

Nick Kitto
  • 5,628
  • 2
  • 13
  • 23