From f5174ee66ed244fa72a7cfe94e5a24d7c8c4c58c Mon Sep 17 00:00:00 2001 From: scippio Date: Mon, 7 Nov 2016 18:49:02 +0100 Subject: [PATCH] ternary operator --- .gitignore | 1 + lib/parser.js | 26 +++++++++++++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 8ae7939..719c850 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ tmp docs/docs/*.json docs/coverage.html build/ +.tags diff --git a/lib/parser.js b/lib/parser.js index 0c94ea9..e45ef72 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -617,24 +617,42 @@ exports.parse = function (swig, source, opts, tags, filters) { return token; } + function isTernary(chunk){ + var ternexp = RegExp('^'+varOpen+'\\s*([\\w"\']+)\\s*\\?\\s*([\\w"\']+)\\s*:\\s*([\\w"\']+)\\s*'+varClose+'$|^'+varOpen+'\\s*([\\w"\']+)\\s*\\?:\\s*([\\w"\']+)\\s*'+varClose+'$','i'); + return chunk.match(ternexp) + } + /*! * Loop over the source, split via the tag/var/comment regular expression splitter. * Send each chunk to the appropriate parser. */ - utils.each(source.split(splitter), function (chunk) { + var chunksToParser = function (chunk) { var token, lines, stripPrev, prevToken, prevChildToken; if (!chunk) { return; } + // Ternary operator + var ternary = isTernary(chunk); + if(ternary !== null){ + var ternarySource; + if(ternary[1] === undefined){ + ternarySource = '{% if '+ternary[4]+' %}{{'+ternary[4]+'}}{% else %}{{'+ternary[5]+'}}{% endif %}'; + } else { + ternarySource = '{% if '+ternary[1]+' %}{{'+ternary[2]+'}}{% else %}{{'+ternary[3]+'}}{% endif %}'; + } + utils.each(ternarySource.split(splitter), chunksToParser); + return; + } + // Is a variable? if (!inRaw && utils.startsWith(chunk, varOpen) && utils.endsWith(chunk, varClose)) { stripPrev = varStripBefore.test(chunk); stripNext = varStripAfter.test(chunk); token = parseVariable(chunk.replace(varStrip, ''), line); // Is a tag? - } else if (utils.startsWith(chunk, tagOpen) && utils.endsWith(chunk, tagClose)) { + } else if(utils.startsWith(chunk, tagOpen) && utils.endsWith(chunk, tagClose)) { stripPrev = tagStripBefore.test(chunk); stripNext = tagStripAfter.test(chunk); token = parseTag(chunk.replace(tagStrip, ''), line); @@ -687,7 +705,9 @@ exports.parse = function (swig, source, opts, tags, filters) { lines = chunk.match(/\n/g); line += lines ? lines.length : 0; - }); + }; + + utils.each(source.split(splitter), chunksToParser); return { name: opts.filename,