Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Created January 3, 2014 13:41
Show Gist options
  • Save bodokaiser/8237992 to your computer and use it in GitHub Desktop.
Save bodokaiser/8237992 to your computer and use it in GitHub Desktop.
Swig custom tag which depending on the argument escapes all var controls.
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