r713 - funjs/public_html/funjs
Author: jruchaud Date: 2014-06-19 11:21:00 +0200 (Thu, 19 Jun 2014) New Revision: 713 Url: http://forge.nuiton.org/projects/sandbox/repository/revisions/713 Log: Improve template ternaire expression Modified: funjs/public_html/funjs/TemplateEngine.js Modified: funjs/public_html/funjs/TemplateEngine.js =================================================================== --- funjs/public_html/funjs/TemplateEngine.js 2014-06-18 14:40:19 UTC (rev 712) +++ funjs/public_html/funjs/TemplateEngine.js 2014-06-19 09:21:00 UTC (rev 713) @@ -1,6 +1,10 @@ TemplateEngine = Class.extend({ - REGEXP_VAR : /{{(\??)(.+?)}}/g, + // {{test}} + // {{test ?}} + // {{test ? value : other}} + // {{! test ? value : other}} + REGEXP_VAR : /{{\s*(!?)\s*(\w+)\s*(\?)?\s*((\w+)\s*:\s*(\w+))?\s*}}/g, load: function(scriptId, node, data) { var self = this; @@ -43,11 +47,35 @@ parseText: function(element, data) { var text = element.nodeValue; - element.nodeValue = text.replace(this.REGEXP_VAR, function(match, g1, g2) { - if (g1 == "?" && !data[g2]) return ""; // Optionnal value + element.nodeValue = this.parseExpression(text, data); + }, + + parseExpression : function(exp, data) { + var self = this; + + return exp.replace(this.REGEXP_VAR, function(match, negation, test, conditionMark, values, trueValue, falseValue) { - return data[g2]; + var result = self.parseValue(test, data); + + if (values == null) { + if (conditionMark == "?" && result == null) { + result = ""; + } + + } else { + result = negation == "!" ^ result ? self.parseValue(trueValue, data) : self.parseValue(falseValue, data); + } + + return result; }); + }, + + parseValue : function(value, data) { + if (data[value] instanceof Function) { + return data[value].call(data); + } else { + return data[value]; + } } }); \ No newline at end of file
participants (1)
-
jruchaud@users.nuiton.org