Skip to content

Commit

Permalink
fix: add guard to if & unless helpers
Browse files Browse the repository at this point in the history
fixes #1548

- add a guard to show readable syntax error for if / unless helper
- prevents against 3 different errors that can be generated by different systax errors
  • Loading branch information
ErisDS committed Oct 25, 2019
1 parent a9514b8 commit 87d78d3
Show file tree
Hide file tree
Showing 3 changed files with 5,857 additions and 7 deletions.
5 changes: 4 additions & 1 deletion lib/handlebars/helpers/if.js
@@ -1,8 +1,10 @@
import {isEmpty, isFunction} from '../utils';
import { isEmpty, isFunction } from '../utils';
import Exception from '../exception';

export default function(instance) {
instance.registerHelper('if', function(conditional, options) {
if (isFunction(conditional)) { conditional = conditional.call(this); }
if (arguments.length != 2) { throw new Exception('#if requires exactly one argument');}

// Default behavior is to render the positive path if the value is truthy and not empty.
// The `includeZero` option may be set to treat the condtional as purely not empty based on the
Expand All @@ -15,6 +17,7 @@ export default function(instance) {
});

instance.registerHelper('unless', function(conditional, options) {
if (arguments.length != 2) { throw new Exception('#unless requires exactly one argument');}
return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn, hash: options.hash});
});
}
20 changes: 14 additions & 6 deletions spec/helpers.js
Expand Up @@ -767,29 +767,37 @@ describe('helpers', function() {
});
});

describe('malformed if', function() {
describe('malformed if/unless', function() {
it('if with too few arguments, string', function() {
var template = CompilerContext.compile('{{#if}}{{/if}}');
shouldThrow(function() {

template({});
}, undefined, /#if requires exactly one argument/);
});

it('if with too many arguments, string', function() {
var template = CompilerContext.compile('{{#if test "string"}}{{/if}}');
shouldThrow(function() {

template({});
}, undefined, /Cannot read property 'includeZero' of undefined/);
}, undefined, /#if requires exactly one argument/);
});

it('if with too many arguments, undefined', function() {
var template = CompilerContext.compile('{{#if test undefined}}{{/if}}');
it('unless with too many arguments, undefined', function() {
var template = CompilerContext.compile('{{#unless test undefined}}{{/unless}}');
shouldThrow(function() {

template({});
}, undefined, /Cannot read property 'hash' of undefined/);
}, undefined, /#unless requires exactly one argument/);
});

it('if with too many arguments, null', function() {
var template = CompilerContext.compile('{{#if test null}}{{/if}}');
shouldThrow(function() {

template({});
}, undefined, /Cannot read property 'hash' of null/);
}, undefined, /#if requires exactly one argument/);
});
});
});

0 comments on commit 87d78d3

Please sign in to comment.