Skip to content

Commit

Permalink
Support negative length in slice filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Nov 8, 2023
1 parent 9db42d1 commit 8abe3ef
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/twig.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -644,9 +644,13 @@ module.exports = function (Twig) {
// Default to start of string
const start = params[0] || 0;
// Default to length of string
const length = params.length > 1 ? params[1] : value.length;
let length = params.length > 1 ? params[1] : value.length;
// Handle negative start values
const startIndex = start >= 0 ? start : Math.max(value.length + start, 0);
// Handle negative length values
if (length < 0) {
length = value.length - startIndex + length;
}

if (Twig.lib.is('Array', value)) {
const output = [];
Expand Down

0 comments on commit 8abe3ef

Please sign in to comment.