【问题标题】:Using array to replace hardcodded if else使用数组替换硬编码 if else
【发布时间】:2019-12-04 16:48:00
【问题描述】:

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

【问题讨论】:

    标签: handlebars.js jsreport


    【解决方案1】:

    你可以这样做:

    • 在脚本中注册 fielddate,因为您已经在尝试 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}}
    

    --

    • helper 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

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 2016-08-03
      • 2014-11-29
      • 1970-01-01
      • 2021-07-04
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多