diff --git a/lib/helpers.js b/lib/helpers.js index 5ef57f01..c613c47d 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -374,7 +374,7 @@ exports.setVar = function (varName, argument) { }; exports.parseIfArgs = function (args, parser) { - var operators = ['==', '<', '>', '!=', '<=', '>=', '===', '!==', '&&', '||', 'in', 'and', 'or'], + var operators = ['==', '<', '>', '!=', '<=', '>=', '===', '!==', '&&', '||', 'in', 'and', 'or', 'mod', '%'], errorString = 'Bad if-syntax in `{% if ' + args.join(' ') + ' %}...', tokens = [], prevType, @@ -416,7 +416,7 @@ exports.parseIfArgs = function (args, parser) { if (prevType === 'operator') { throw new Error(errorString); } - value = value.replace('and', '&&').replace('or', '||'); + value = value.replace('and', '&&').replace('or', '||').replace('mod', '%'); tokens.push({ value: value }); diff --git a/tests/node/tags/if.test.js b/tests/node/tags/if.test.js index b4e6175b..650ea8db 100644 --- a/tests/node/tags/if.test.js +++ b/tests/node/tags/if.test.js @@ -43,6 +43,37 @@ describe('Tag: if', function () { expect(tpl({ foo: 'b', bar: ['a', 'b', 'c'] })).to.equal('hi!'); }); + it('can use the "%" operator', function () { + var tpl = swig.compile('{% if foo % 2 == 0 %}hi!{% endif %}'); + expect(tpl({ foo: 4 })).to.equal('hi!'); + + tpl = swig.compile('{% if foo % 2 == 0 %}hi!{% endif %}'); + expect(tpl({ foo: 5 })).to.equal(''); + + tpl = swig.compile('{% if foo % 2 %}hi!{% endif %}'); + expect(tpl({ foo: 4 })).to.equal(''); + + tpl = swig.compile('{% if foo % 2 %}hi!{% endif %}'); + expect(tpl({ foo: 3 })).to.equal('hi!'); + + }); + + it('can use the "mod" operator', function () { + var tpl = swig.compile('{% if foo mod 2 == 0 %}hi!{% endif %}'); + expect(tpl({ foo: 4 })).to.equal('hi!'); + + tpl = swig.compile('{% if foo mod 2 == 0 %}hi!{% endif %}'); + expect(tpl({ foo: 5 })).to.equal(''); + + tpl = swig.compile('{% if foo mod 2 %}hi!{% endif %}'); + expect(tpl({ foo: 4 })).to.equal(''); + + tpl = swig.compile('{% if foo mod 2 %}hi!{% endif %}'); + expect(tpl({ foo: 3 })).to.equal('hi!'); + + }); + + it('throws on bad conditional syntax', function () { var fn1 = function () { swig.compile('{% if foo bar %}{% endif %}');