Add support for flow and global context in Template node (#1048)

* Enable tests for flow and global context

* Add support for flow and global context in Template node

* Handle missing node context
This commit is contained in:
Adam Hořčica
2016-11-16 15:08:14 +01:00
committed by Nick O'Leary
parent d63996eea1
commit be18cc9f2d
3 changed files with 99 additions and 15 deletions

View File

@@ -67,6 +67,7 @@
}</pre>
<p>The resulting property will be:
<pre>Hello Fred. Today is Monday</pre>
<p>It is possible to use property from flow context or global context. Just use <code>{{flow.name}}</code> or <code>{{global.name}}</code>.
<p>By default, mustache will escape any HTML entities in the values it substitutes.
To prevent this, use <code>{{{triple}}}</code> braces.
</script>

View File

@@ -18,6 +18,39 @@ module.exports = function(RED) {
"use strict";
var mustache = require("mustache");
/**
* Custom Mustache Context capable to resolve message property and node
* flow and global context
*/
function NodeContext(msg, nodeContext) {
this.msgContext = new mustache.Context(msg);
this.nodeContext = nodeContext;
}
NodeContext.prototype = new mustache.Context();
NodeContext.prototype.lookup = function (name) {
// try message first:
var value = this.msgContext.lookup(name);
if (value !== undefined) {
return value;
}
// try node context:
var dot = name.indexOf(".");
if (dot > 0) {
var contextName = name.substr(0, dot);
var variableName = name.substr(dot + 1);
if (contextName === "flow" && this.nodeContext.flow) {
return this.nodeContext.flow.get(variableName);
}
else if (contextName === "global" && this.nodeContext.global) {
return this.nodeContext.global.get(variableName);
}
}
}
function TemplateNode(n) {
RED.nodes.createNode(this,n);
this.name = n.name;
@@ -31,7 +64,7 @@ module.exports = function(RED) {
try {
var value;
if (node.syntax === "mustache") {
value = mustache.render(node.template,msg);
value = mustache.render(node.template, new NodeContext(msg, node.context()));
} else {
value = node.template;
}