Skip to content

Commit 9db42d1

Browse files
committedNov 8, 2023
Support variables in slice filter shorthand.
1 parent f08598b commit 9db42d1

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed
 

‎src/twig.expression.js

+33-5
Original file line numberDiff line numberDiff line change
@@ -576,14 +576,14 @@ module.exports = function (Twig) {
576576
},
577577
{
578578
type: Twig.expression.type.slice,
579-
regex: /^\[(\d*:\d*)\]/,
579+
regex: /^\[(-?\w*:-?\w*)\]/,
580580
next: Twig.expression.set.operationsExtended,
581581
compile(token, stack, output) {
582582
const sliceRange = token.match[1].split(':');
583583

584584
// SliceStart can be undefined when we pass parameters to the slice filter later
585-
const sliceStart = (sliceRange[0]) ? parseInt(sliceRange[0], 10) : undefined;
586-
const sliceEnd = (sliceRange[1]) ? parseInt(sliceRange[1], 10) : undefined;
585+
const sliceStart = sliceRange[0];
586+
const sliceEnd = sliceRange[1];
587587

588588
token.value = 'slice';
589589
token.params = [sliceStart, sliceEnd];
@@ -596,11 +596,39 @@ module.exports = function (Twig) {
596596

597597
output.push(token);
598598
},
599-
parse(token, stack) {
599+
parse(token, stack, context) {
600600
const input = stack.pop();
601-
const {params} = token;
601+
let {params} = token;
602602
const state = this;
603603

604+
if (parseInt(params[0], 10).toString() === params[0]) {
605+
params[0] = parseInt(params[0], 10);
606+
} else {
607+
const value = context[params[0]];
608+
if (state.template.options.strictVariables && value === undefined) {
609+
throw new Twig.Error('Variable "' + params[0] + '" does not exist.');
610+
}
611+
612+
params[0] = value;
613+
}
614+
615+
if (params[1]) {
616+
if (parseInt(params[1], 10).toString() === params[1]) {
617+
params[1] = parseInt(params[1], 10);
618+
} else {
619+
const value = context[params[1]];
620+
if (state.template.options.strictVariables && value === undefined) {
621+
throw new Twig.Error('Variable "' + params[1] + '" does not exist.');
622+
}
623+
624+
if (value === undefined) {
625+
params = [params[0]];
626+
} else {
627+
params[1] = value;
628+
}
629+
}
630+
}
631+
604632
stack.push(Twig.filter.call(state, token.value, input, params));
605633
}
606634
},

0 commit comments

Comments
 (0)
Please sign in to comment.