KotlinJs: как написать HandleBarJS в kotlin

#javascript #kotlin #handlebars.js #kotlin-multiplatform #kotlin-js

#javascript #kotlin #handlebars.js #kotlin-мультиплатформенный #kotlin-js

Вопрос:

У меня есть запущенный JS-код, который использует HandleBarJs:

 var fs = require('fs');
let template = fs.readFileSync('template.txt', 'utf8')
let submissionJson = fs.readFileSync('submission.json', 'utf8')

var handleBarJs = require('handlebars');
handleBarJs.registerHelper('eq', function (firstParam, secondParam, options) {
    if (firstParam == secondParam) return options.fn(this); else return options.inverse(this);
})
handleBarJs.registerHelper('contains', function (firstParam, secondParam, options) {
    if (firstParam.includes(secondParam)) return options.fn(this); else return options.inverse(this);
})
var compiledTemplate = handleBarJs.compile(template)
var output = compiledTemplate(JSON.parse(submissionJson));
console.log(output);
 

Я хочу написать тот же код в Kotlin JS. Это то, что я пробовал:

 actual class HandleBarService actual constructor() {

    private val handleBars = require("handlebars")

    actual fun generateCertificateString(template: String, data: Any): String {

        println("Input Template:n$template")
//        println("Input Json:n${data}")

        val eqHelper = lambda@ fun(firstParam: String, secondParam: String, options: dynamic) {
            println("firstParam: $firstParam secondParam: $secondParam")
            if (firstParam == secondParam) return options.fn(lambda@ this) else return options.inverse(lambda@ this)
        }
        val containsHelper = lambda@ fun(firstParam: List<String>, secondParam: String, options: dynamic) {
            if (firstParam.contains(secondParam)) return options.fn(lambda@ this) else return options.inverse(lambda@ this)
        }

        handleBars.registerHelper("eq", eqHelper)
        handleBars.registerHelper("contains", containsHelper)

        val handlebarTemplate = handleBars.compile(template)
        val dataTemplate = handlebarTemplate(data)
        println("HandleBar Output:n$dataTemplate")
        return dataTemplate
    }
}
 

Шаблон:

 <b>List Of Violations For </b>
<br></br>
{{#each modules}}
    {{#eq type 'checklist' }}
        {{#each data.checklistItemResults}}
            {{#contains violation.finalActions 'order'}}
                <br><b>Requirement:</b></br>
                <br> {{checklistItemDescription}} </br>
                <br><b>Violation:</b></br>
                <br>{{violation.description}}</br>
                <br><b>CorrectiveActions:</b></br>
                <br>{{#each violation.correctiveActions}} {{this}} {{/each}}</br>
            {{/contains}}
        {{/each}}
    {{/eq}}
{{/each}}
 

Json:

 {
  "modules": [
    {
      "data": {
        "checklistItemResults": [
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "Failed to properly register all regulated tanks with the Department.",
              "type": "Major",
              "correctiveActions": [
                "Submit a completed Underground Storage Tank Facility Certification Questionnaire: on the effective date of this document."
              ]
            }
          },
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "Failed to make the Registration Certificate available.",
              "type": "Major",
              "correctiveActions": [
                "Make registration certificate available."
              ]
            }
          },
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "Failed to submit an amended UST Questionnaire to reflect changes in status made to the UST systems.  Specifically, (provide details)",
              "type": "Minor",
              "correctiveActions": [
                "Submit a completed Underground Storage Tank Facility Certification Questionnaire: within 30 days of receipt of this document."
              ]
            }
          },
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "Failed to have Financial Responsibility Assurance Mechanism as required.",
              "type": "Major",
              "correctiveActions": [
                "Immediately obtain Financial Responsibility as required."
              ]
            }
          },
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "The owner and operator failed to maintain records of operation and maintenance walkthrough inspections for five years. ",
              "type": "Minor",
              "correctiveActions": [
                "Comply with rule/regulation: within 30 days of receipt of this document."
              ]
            }
          },
          {
            "checklistItemDescription": "",
            "violation": {
              "description": "Release Response Plan not available for the inspection.",
              "type": "Minor",
              "correctiveActions": [
                "Make Release Response Plan available."
              ]
            }
          }
        ]
      },
      "type": "checklist"
    }
  ]
}
 

Ожидаемый результат:

 <b>List Of Violations For </b>
<br></br>
                <br><b>Requirement:</b></br>
                <br> Any person that owns or operates an underground storage tank system shall register each tank system with the Department. [N.J.A.C. 7:14B- 2.1(a)] </br>
                <br><b>Violation:</b></br>
                <br>Failed to properly register all regulated tanks with the Department.</br>
                <br><b>CorrectiveActions:</b></br>
                <br> Submit a completed Underground Storage Tank Facility Certification Questionnaire: on the effective date of this document. </br>
                <br><b>Requirement:</b></br>
                <br> In accordance with N.J.A.C. 7:14B-5.6(b), the owner and operator shall maintain records of operation and maintenance walkthrough inspections for five years. The record shall identify the areas checked, whether each area checked was acceptable or required corrective action, a description of any corrective action taken, and delivery records if spill prevention equipment is checked less than every 30 days due to infrequent deliveries. [N.J.A.C. 7:14B- 5.12(c)] </br>
                <br><b>Violation:</b></br>
                <br>The owner and operator failed to maintain records of operation and maintenance walkthrough inspections for five years. </br>
                <br><b>CorrectiveActions:</b></br>
                <br> Comply with rule/regulation: within 30 days of receipt of this document. </br>
                <br><b>Requirement:</b></br>
                <br> No person shall operate (nor cause to be operated) a significant source or control apparatus serving the significant source without a valid operating certificate. [N.J.A.C. 7:27- 8.3(b)] </br>
                <br><b>Violation:</b></br>
                <br>Release Response Plan not available for the inspection.</br>
                <br><b>CorrectiveActions:</b></br>
                <br> Make Release Response Plan available. </br>
 

Фактический результат:

 <b>List Of Violations For </b>
<br></br>
 

Я получаю желаемый результат с помощью чистого кода JS, но не с помощью Kotlin JS, может кто-нибудь помочь с этим?

Я думаю, что проблема связана с регистрацией помощников. Не уверен, как бы мы написали this ключевое слово внутри lambda, чтобы HandleBarService также не указывать, я просмотрел документацию по этим выражениям

Комментарии:

1. Можете ли вы рассказать нам, что происходит?

2. @ClaudeBrisson Я отредактировал вопрос. Можете ли вы проверить еще раз?