Skip to content

Commit

Permalink
add some necessary exceptions to strict_variables = true handling
Browse files Browse the repository at this point in the history
  • Loading branch information
d--j committed Feb 26, 2021
1 parent 071be04 commit b3f0d67
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/twig.expression.js
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,25 @@ module.exports = function (Twig) {
return Twig.expression.resolveAsync.call(state, context[token.value], context)
.then(value => {
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + token.value + '" does not exist.');
let skipException = false;
if (token.peek) {
const {peek} = token;
if (peek.type === Twig.expression.type.filter && peek.value === 'default') {
skipException = true;
}

if (peek.type === Twig.expression.type.operator.binary && peek.value === '??') {
skipException = true;
}

if (peek.type === Twig.expression.type.test && peek.filter === 'defined') {
skipException = true;
}
}

if (!skipException) {
throw new Twig.Error('Variable "' + token.value + '" does not exist.');
}
}

stack.push(value);
Expand Down Expand Up @@ -1255,6 +1273,7 @@ module.exports = function (Twig) {

while (tokens.length > 0) {
token = tokens.shift();
token.peek = tokens[0];
tokenTemplate = Twig.expression.handler[token.type];

Twig.log.trace('Twig.expression.compile: ', 'Compiling ', token);
Expand Down
32 changes: 32 additions & 0 deletions test/test.options.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,36 @@ describe('Twig.js Optional Functionality ->', function () {
}
});
});

describe('should not throw an error when `strict_variables` set to `true`', function () {
const filter = twig({
rethrow: true,
strict_variables: true,
data: '{{ test|default }}'
});

const nullcoalescing = twig({
rethrow: true,
strict_variables: true,
data: '{{ test ?? \'test\' }}'
});

const test = twig({
rethrow: true,
strict_variables: true,
data: '{% if test is defined %}{% endif %}'
});

it('For undefined variables with default filter', function () {
filter.render();
});

it('For undefined variables with ?? operator', function () {
nullcoalescing.render();
});

it('For undefined variables with defined test', function () {
test.render();
});
});
});

0 comments on commit b3f0d67

Please sign in to comment.