Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});
});
});