Search code examples
handlebars.jsjsreport

Using array to replace hardcodded if else


working playground

The following code is my current working code:

{{#each ../cellHeaders}} 
    {{#if_eq this 'Date'}}
    <c t="d" s="4">
        <v>{{lookup ../this this}}</v>
    </c>
    {{else}}
        {{#if_eq this 'birthday'}}
        <c t="d" s="4">
          <v>{{lookup ../this this}}</v>
        </c>
        {{else}}
        <c t="inlineStr" s="2">
        <is>
          <t>{{lookup ../this this}}</t>
        </is>
        </c>
        {{/if_eq}} 
    {{/if_eq}} 
{{/each}}

I would like to replace the manual string inputted on if else by using something like:

{{#each ../cellHeaders}} 
    {{#each ../fielddate}} 
    {{#if_eq ../../this this}}
    <c t="d" s="4">
        <v>{{lookup ../../this ../this}}</v>
    </c>
    {{else}}
    <c t="inlineStr" s="2">
      <is>
        <t>{{lookup ../../this ../this}}</t>
      </is>
    </c>
    {{/if_eq}} 
    {{/each}}
{{/each}}

But it's not working. jsreport part on italic: I've declared the fielddate: var fielddate= ['date', 'birthday']; and registered it: req.data.fielddate = fielddate;

What I expect was using an array to replace the process on my current working code: e.g: {{#if_eq this 'Date'}} or {{#if_eq this 'est_delivery'}} which is violating DRY rule.

I've tried dereferencing the parent as this answer suggested but apparently it's not working since my jsreport wasn't generating anything.

Any idea?

Example working playground


Solution

  • you can do something like this:

    • register the fielddate in script as you were already trying var fielddate= ['date', 'birthday']; req.data.fielddate = fielddate;

    • change your each part to this

    --

    {{#each ../cellHeaders}} 
        {{#ifFieldDate this @root.fielddate}}
            <c t="d" s="4">
                <v>{{lookup ../this this}}</v>
            </c>
        {{else}}
            <c t="inlineStr" s="2">
                <is>
                    <t>{{lookup ../this this}}</t>
                </is>
            </c>
        {{/ifFieldDate}}
    {{/each}}
    

    --

    • the helper ifFieldDate should be defined like this

    --

    function ifFieldDate (value, fieldNames, opts) {
      const fields = fieldNames.map((f) => f.toLowerCase())
    
      if (fields.includes(value.toLowerCase())) {
          return opts.fn(this);
      } else {
        return opts.inverse(this);
      } 
    }
    

    --

    live example here