From a0067eaf3cb93b2d9a1f6edf927ddd2ea6280304 Mon Sep 17 00:00:00 2001 From: Amit Gupta Date: Wed, 20 Nov 2024 14:24:50 -0800 Subject: [PATCH] support lists with variables as index rather than just numbers --- lib/Template/Liquid/Context.pm | 11 ++++++++++- t/0200_tags/02001_for.t | 6 ++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/Template/Liquid/Context.pm b/lib/Template/Liquid/Context.pm index 6aa5ad2..ea5ca35 100644 --- a/lib/Template/Liquid/Context.pm +++ b/lib/Template/Liquid/Context.pm @@ -138,7 +138,16 @@ sub get { # print STDERR "DEBUG:obj property. var=$var. 1=$1,2=$2"; my $obj = $s->get($1); - return $obj->{$2} if $obj; + my $objreftype = ref $obj; + return $obj->{$2} if $objreftype eq "HASH"; + + if($objreftype eq 'ARRAY') { + # resolve the scope variable into an array index + my $a_idx = $s->get($2); + # print STDERR "\nDEBUG:a_idx=$a_idx"; + return @$obj[$a_idx] if @$obj[$a_idx]; + } + return; # return if nothing } STEP: while (@path) { diff --git a/t/0200_tags/02001_for.t b/t/0200_tags/02001_for.t index 37099c6..8e492f6 100644 --- a/t/0200_tags/02001_for.t +++ b/t/0200_tags/02001_for.t @@ -7,6 +7,12 @@ use Template::Liquid; #{% assign items = "foo"%}{%for item in items%}{{item}}{%endfor%} $|++; # +is( Template::Liquid->parse( + <<'TEMPLATE')->render(array => "foo,bar"), <<'EXPECTED', 'string split with index'); +{% assign items = array | split: "," %}{% for i in (0..2) %}{{items[i]}}{%endfor%} +TEMPLATE +foobar +EXPECTED is( Template::Liquid->parse( <<'TEMPLATE')->render(array => "foo,bar"), <<'EXPECTED', 'string split'); {% assign items = array | split: "," %}{%for item in items%}{{item}}{%endfor%}