Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for key references #298

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 26 additions & 6 deletions mustache.js
Expand Up @@ -30,7 +30,8 @@
var nonSpaceRe = /\S/;
var eqRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
var tagRe = /#|\^|\/|>|\{(?!\{)|&|=|!/;
var refRe = /\{\{\s*([a-zA-Z0-9\.\-\_]+)\s*\}\}/;

var _test = RegExp.prototype.test;
var _toString = Object.prototype.toString;
Expand Down Expand Up @@ -105,8 +106,8 @@
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function (re) {
var match, pos = this.tail.search(re);
Scanner.prototype.scanUntil = function (re, opp) {
var match, tag, pos = this.tail.search(re);

switch (pos) {
case -1:
Expand All @@ -121,6 +122,12 @@
match = this.tail.substring(0, pos);
this.tail = this.tail.substring(pos);
this.pos += pos;
if (opp && opp.test(match)) {
tag = re.exec(this.tail)[0];
this.pos += tag.length;
this.tail = this.tail.substring(tag.length);
match += tag + this.scanUntil(re);
}
}

return match;
Expand Down Expand Up @@ -238,7 +245,7 @@
function renderTokens(tokens, writer, context, template) {
var buffer = '';

var token, tokenValue, value;
var token, tokenValue, value, match, ref;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
tokenValue = token[1];
Expand Down Expand Up @@ -288,6 +295,16 @@
value = context.lookup(tokenValue);
if (value != null) buffer += exports.escape(value);
break;
case "name-ref":
if (match = refRe.exec(tokenValue)) {
ref = context.lookup(match[1]);
value = context.lookup(tokenValue.replace(refRe, ref));
}

if (value != null && value != undefined) {
buffer += exports.escape(value);
}
break;
case 'text':
buffer += tokenValue;
break;
Expand Down Expand Up @@ -417,7 +434,6 @@

tokens.push(['text', chr, start, start + 1]);
start += 1;

// Check for whitespace on the current line.
if (chr == '\n') stripSpace();
}
Expand All @@ -442,7 +458,11 @@
scanner.scanUntil(tagRes[1]);
type = '&';
} else {
value = scanner.scanUntil(tagRes[1]);
value = scanner.scanUntil(tagRes[1], tagRes[0]);
if (tagRes[0].test(value)) {
type = 'name-ref';
hasTag = false;
}
}

// Match the closing tag.
Expand Down