1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00
node-red/nodes/core/core/80-template.js

55 lines
1.8 KiB
JavaScript
Raw Normal View History

2013-09-05 16:02:48 +02:00
/**
* Copyright 2013, 2016 IBM Corp.
2013-09-05 16:02:48 +02:00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
2014-05-04 00:32:04 +02:00
module.exports = function(RED) {
"use strict";
2014-05-04 00:32:04 +02:00
var mustache = require("mustache");
2014-05-05 09:58:53 +02:00
2014-05-04 00:32:04 +02:00
function TemplateNode(n) {
RED.nodes.createNode(this,n);
this.name = n.name;
this.field = n.field || "payload";
2014-05-04 00:32:04 +02:00
this.template = n.template;
this.syntax = n.syntax || "mustache";
2016-01-04 16:03:33 +01:00
this.fieldType = n.fieldType || "msg";
2016-01-04 16:03:33 +01:00
var node = this;
node.on("input", function(msg) {
2014-09-08 22:10:06 +02:00
try {
var value;
if (node.syntax === "mustache") {
value = mustache.render(node.template,msg);
} else {
value = node.template;
}
2016-01-04 16:03:33 +01:00
if (node.fieldType === 'msg') {
RED.util.setMessageProperty(msg,node.field,value);
} else if (node.fieldType === 'flow') {
node.context().flow.set(node.field,value);
} else if (node.fieldType === 'global') {
node.context().global.set(node.field,value);
}
node.send(msg);
2014-09-08 22:10:06 +02:00
} catch(err) {
node.error(err.message);
2014-05-05 09:58:53 +02:00
}
2014-05-04 00:32:04 +02:00
});
}
2014-05-05 09:58:53 +02:00
2014-05-04 00:32:04 +02:00
RED.nodes.registerType("template",TemplateNode);
RED.library.register("templates");
2013-09-05 16:02:48 +02:00
}