Created
January 3, 2014 13:41
-
-
Save bodokaiser/8237992 to your computer and use it in GitHub Desktop.
Swig custom tag which depending on the argument escapes all var controls.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var swig = require('swig'); | |
var source = ''; | |
source += '{% escapes true %}'; | |
source += '<li>{{ name }}</li>'; | |
source += '{% endescapes %}'; | |
swig.setTag('escapes', parse, compile, true, false); | |
console.log(swig.render(source)); | |
function parse(str, line, parser, types) { | |
parser.on(types.COMPARATOR, function (token) { | |
if (this.isLast) { | |
throw new Error('Unexpected logic "' + token.match + '" on line ' + line + '.'); | |
} | |
if (this.prevToken.type === types.NOT) { | |
throw new Error('Attempted logic "not ' + token.match + '" on line ' + line + '. Use !(foo ' + token.match + ') instead.'); | |
} | |
this.out.push(token.match); | |
}); | |
parser.on(types.NOT, function (token) { | |
if (this.isLast) { | |
throw new Error('Unexpected logic "' + token.match + '" on line ' + line + '.'); | |
} | |
this.out.push(token.match); | |
}); | |
parser.on(types.BOOL, function (token) { | |
this.out.push(token.match); | |
}); | |
parser.on(types.LOGIC, function (token) { | |
if (!this.out.length || this.isLast) { | |
throw new Error('Unexpected logic "' + token.match + '" on line ' + line + '.'); | |
} | |
this.out.push(token.match); | |
this.filterApplyIdx.pop(); | |
}); | |
return true; | |
}; | |
function compile(compiler, args, content, parents, options, blockName) { | |
return 'if (!' + args.join(' ') + ') {\n' + | |
compiler(content, parents, options, blockName) + '\n' + | |
'}'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment