Skip to content

Commit

Permalink
Prep for reporting location of template compilation errors.
Browse files Browse the repository at this point in the history
Step 3: unroll main substitution into an explicit loop in
which we can track where each subst. occurs. With this and
the line-break index we build up front, we'll be able to
determine the source line and start/end line inded for
each replaced tag, and can then report that information
when a compilation failure (i.e. bad template syntax) is
detected.
  • Loading branch information
laurie71 committed Apr 6, 2011
1 parent c331f70 commit c3016e3
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions lib/jqtpl.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,36 @@ function unescape(args) {
* @export
*/
function buildTmplFn(markup) {
var source = '', breaks = [], tagexp, breakexp, matched, replace, start, finish;
tagexp = /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g;
breakexp = /(?:\r?\n)/g;

// Build index of line-break indexes for source error reporting
breaks = [0];
while ((matched = breakexp.exec(markup)) != null) {
breaks.push(matched.index + matched[0].length);
}

// Convert the template into pure JavaScript
markup = markup
.trim()
.replace(/([\\"])/g, '\\$1')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\$\{([^\}]*)\}/g, '{{= $1}}');
markup = markup
.replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
function(all, slash, type, fnargs, target, parens, args) {

finish = 0;
while ((matched = tagexp.exec(markup)) != null) {
replace = tagsubst.apply(this, matched);

start = matched.index;
source += markup.slice(finish, start);
finish = start + matched[0].length;
source += replace;
}
source += markup.slice(finish);

function tagsubst(all, slash, type, fnargs, target, parens, args) {
var tag = exports.tag[type], def, expr, exprAutoFnDetect;

if (!tag) {
Expand Down Expand Up @@ -234,17 +254,16 @@ function buildTmplFn(markup) {
.split('$2').join(fnargs || def.$2 || '') +
'_.push("';
}
);

var source = (
'var call,_=[],$data=$item.data;' +
// Introduce the data as local variables using with(){}
'with($data){_.push("\\n' +
markup +
source +
'");}' +
'return _.join("");'
);

return new Function('$', '$item', source);
}

Expand Down

0 comments on commit c3016e3

Please sign in to comment.