0

I have data handed to me by the server.

I do not want the container <p> to be present if there is no data item. But there could be several data items or 1 data item, if any exist I need a <p> wrapper.

Ideally, I am looking for some kind of #ifor helper which will accept any number of arguments. Is this possible?

{{#ifor firstname||lastname||nickname||age}}
<p>
  {{#if firstname}}
    <span class="firtname">{{firstname}}</span>
  {{/if}}

  {{#if lastname}}
    {{lastname}}
  {{/if}}

  {{#if age}}
   Age: {{age}}
  {{/if}}

  {{#if nickname}}
    - ( {{type}} )
  {{/if}}
</p>
{{/if}}
nikoshr
  • 31,776
  • 30
  • 87
  • 102
Fasani
  • 2,009
  • 19
  • 22
  • Possible duplicate of http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional ;-) – Aegis Aug 13 '13 at 15:32

1 Answers1

1

A simple solution would be to write a helper that accepts the attributes you wish to test, without the OR operator. You then iterate over the arguments and check if they match a truth test :

Handlebars.registerHelper('ifor', function() {
    var l, opts;

    opts = Array.prototype.pop.call(arguments);
    for (l = arguments.length-1; l>=0; l--) {
        // test against undefined if you prefer
        //if (typeof(arguments[l])!=='undefined')

        if (arguments[l])
            return opts.fn(this);
    }

    return opts.inverse(this);
});

And a Fiddle http://jsfiddle.net/G5Vhc/1/

nikoshr
  • 31,776
  • 30
  • 87
  • 102