使用数组替换 hardcodded if else

Using array to replace hardcodded if else

working playground

以下代码是我目前的工作代码:

{{#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}}

我想用类似的东西替换在 if else 上输入的手动字符串:

{{#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}}

但它不起作用。 斜体的jsreport部分: 我已经声明了字段日期:var fielddate= ['date', 'birthday']; 并注册:req.data.fielddate = fielddate;

我期望的是使用数组替换我当前工作代码中的进程:例如:{{#if_eq this 'Date'}}{{#if_eq this 'est_delivery'}} 违反了 DRY 规则。

我已经尝试按照 this answer 的建议取消对父级的引用,但显然它不起作用,因为我的 jsreport 没有生成任何东西。

有什么想法吗?

例子working playground

你可以这样做:

  • 在脚本中注册字段日期,因为您已经尝试过 var fielddate= ['date', 'birthday']; req.data.fielddate = fielddate;

  • 将你的每个部分改成这个

--

{{#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}}

--

  • 助手ifFieldDate应该这样定义

--

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);
  } 
}

--

实例here