Skip to content

Support variables in slice filter shorthand #881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 16, 2023
Merged
Changes from 1 commit
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
Next Next commit
Support variables in slice filter shorthand.
  • Loading branch information
antoineveldhoven committed Nov 8, 2023
commit 9db42d183e6d5c2bd7c3108a74f4f3161ed45244
38 changes: 33 additions & 5 deletions src/twig.expression.js
Original file line number Diff line number Diff line change
Expand Up @@ -576,14 +576,14 @@ module.exports = function (Twig) {
},
{
type: Twig.expression.type.slice,
regex: /^\[(\d*:\d*)\]/,
regex: /^\[(-?\w*:-?\w*)\]/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
const sliceRange = token.match[1].split(':');

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

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

output.push(token);
},
parse(token, stack) {
parse(token, stack, context) {
const input = stack.pop();
const {params} = token;
let {params} = token;
const state = this;

if (parseInt(params[0], 10).toString() === params[0]) {
params[0] = parseInt(params[0], 10);
} else {
const value = context[params[0]];
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + params[0] + '" does not exist.');
}

params[0] = value;
}

if (params[1]) {
if (parseInt(params[1], 10).toString() === params[1]) {
params[1] = parseInt(params[1], 10);
} else {
const value = context[params[1]];
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + params[1] + '" does not exist.');
}

if (value === undefined) {
params = [params[0]];
} else {
params[1] = value;
}
}
}

stack.push(Twig.filter.call(state, token.value, input, params));
}
},
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy