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

Optional automatic prefixing and empty checking #48

Closed
wants to merge 2 commits into from
Closed
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
33 changes: 29 additions & 4 deletions doT.js
Expand Up @@ -20,7 +20,8 @@
varname: 'it', varname: 'it',
strip: true, strip: true,
append: true, append: true,
selfcontained: false selfcontained: false,
emptycheck: false
}, },
template: undefined, //fn, compile template template: undefined, //fn, compile template
compile: undefined //fn, for express compile: undefined //fn, for express
Expand Down Expand Up @@ -75,6 +76,30 @@
return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, ' '); return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, ' ');
} }


function emptyCheck(c, code){

return !c.emptycheck? code : code.replace(/\w+\.\w+/g, function(code){

var i=0,
p,
arr=code.split('.'),
ret=['view']
;

if (arr[0] === c.varname) arr.shift();

while ( p = arr.shift() ){
i = ret.push(ret[i] + '.' + p) - 1;
};

ret.shift();

return ret.join('&&')+'||""';
})
// prefix any single occurances of variables, eg: {{foo}}
.replace(/(?!\W?\w+\.|\.\w+)(^|\W)(\w+)(\W|$)/g, c.varname+'.$2');
}

doT.template = function(tmpl, c, def) { doT.template = function(tmpl, c, def) {
c = c || doT.templateSettings; c = c || doT.templateSettings;
var cse = c.append ? startend.append : startend.split, str, needhtmlencode, sid=0, indv; var cse = c.append ? startend.append : startend.split, str, needhtmlencode, sid=0, indv;
Expand All @@ -89,11 +114,11 @@
.replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,''): str) .replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,''): str)
.replace(/'|\\/g, '\\$&') .replace(/'|\\/g, '\\$&')
.replace(c.interpolate || skip, function(m, code) { .replace(c.interpolate || skip, function(m, code) {
return cse.start + unescape(code) + cse.end; return cse.start + emptyCheck(c, unescape(code)) + cse.end;
}) })
.replace(c.encode || skip, function(m, code) { .replace(c.encode || skip, function(m, code) {
needhtmlencode = true; needhtmlencode = true;
return cse.startencode + unescape(code) + cse.end; return cse.startencode + emptyCheck(c, unescape(code)) + cse.end;
}) })
.replace(c.conditional || skip, function(m, elsecase, code) { .replace(c.conditional || skip, function(m, elsecase, code) {
return elsecase ? return elsecase ?
Expand Down Expand Up @@ -128,4 +153,4 @@
doT.compile = function(tmpl, def) { doT.compile = function(tmpl, def) {
return doT.template(tmpl, null, def); return doT.template(tmpl, null, def);
}; };
}()); }());