如何在节点红色的html文件中生成脚本模板元素

问题描述

我正在寻找一种方法,最好从<script type="text/javascript">部分生成node-red node html definition file<script type="text/html">部分。

背景上下文

我正在创建大量的节点红色节点来访问和/或服务API。 API代表它所代表的不同资源遵循相似的模式,就像您期望的REST API一样。对于API公开的每种方法和资源,这都会导致出现许多相似的节点,例如:get-book-actionget-publisher-actionget-author-action,等等。

我以这样的方式编写了我的节点红色节点:可以简单地定义资源列表(即const resources = ['book','author','series','publisher',...]),并通过为get,{ {1}}等。我还没有解决的事情是如何对编辑器模板部分执行相同的操作,这就是为什么我要问这个问题。

伪示例

我想要这样的东西:

update

解决方法

节点红色节点的.html文件中的脚本块只是作为编辑器页面上div的子级插入到dom中。这意味着您可以使用前端JavaScript的全部功能。

我发现实现此目标的方法如下:

<script type="text/javascript">
(function(RED) {
  const resources = ["author","book","publisher",...];
  resources.forEach(resource => {
    RED.nodes.registerType(`get-${resource}-action`,{...});
    RED.nodes.registerType(`update-${resource}-action`,{...});
    RED.nodes.registerType(`delete-${resource}-action`,{...});
    // other verbs

    // We have to split up the <scr and ipt parts as if either the opening or closing
    // tags appear anywhere in this block it will close the js script block
    $(document.currentScript).parent().append(
      '<scr'+`ipt type="text/html" data-template-name="get-${resource}-action">
        <div class="form-row">
          <label for="node-config-input-name><i class="icon-tag"></i> Name</label>
          <input type="text" id="node-config-input-name">
        </div>
      </scr`+'ipt>'
    );
    // and so on for data-help-name and other verbs
  });
})(RED);
</script>