I've been having a ball creating fun iterative structures in Template Toolkit templates - and then ran into this.
Users, identified by their user_type, last name (lname), and company, make selections numbered 1 to 6. They can make multiple selections. I receive their selections as a string:
For other purposes in the script, I build a hash-based data structure out of all of it:$choices = ",1,2,3,4,5,6,";
$data{$user_type}{$user_company}{$user_lname}{'attribute'}
To store their choices, I split the string into an array, and store the array in a 'choice_list' attribute of that user:
And at one point I want to output a list of choices for each user, grouped by lname, then by company, then by user_type (hence the data structure).$data{$user_type}{$user_company$}{$user_lname}{'choice_list'} = [ @spl +it_list ];
Everything was going perfectly until I added the very last loop to iterate over the choices array:
Perl script snippets:
$choices = ",1,2,3,4,5,6,"; print "Perl script output - <br>choices list before regex = $choices\n +"; #string cleanup $choices =~ s/^,//; $choices =~ s/,$//; print "<br>choices list after regex = $choices\n"; @split_list = split(/,+/, $choices); # debugging output to check split for $i (0 .. $#pub_list) { print "<br>choice $i = $pub_list[$i]\n"; } $data{$user_type}{$user_company$}{$user_lname}{'choice_list'} = [ @spl +it_list ]; $vars = { data => \%data, }; $template->process($template_file, $vars);
Template:
Template output - <br>Choices are:<br> [% FOREACH type IN data.keys.sort %] [% FOREACH company IN data.$type.keys.sort %] [% FOREACH name IN data.$type.$company.keys.sort %] [% FOREACH choice IN data.$type.$company.$name.choice_l +ist %] [% data.$type.$company.$name.choice_list.$choice % +]<br> [% END %] [% END %] [% END %] [% END %]
Output:
I have the right number of breaks in the output, but the choice numbers are shifted - the "1" is missing and there's an extra break after the 6. Is it something to do with the way that I'm referencing the array of choices?Perl script output - <br>choices list before regex = ,1,2,3,4,5,6, <br>choices list after regex = 1,2,3,4,5,6 <br>choice 0 = 1 <br>choice 1 = 2 <br>choice 2 = 3 <br>choice 3 = 4 <br>choice 4 = 5 <br>choice 5 = 6 Template output - <br>Choices are:<br> 2<br> 3<br> 4<br> 5<br> 6<br> <br>
Thanks.
Updated within 60 seconds of original posting, and before any replies, for typo in template loops
In reply to Iterating over hash of arrays in Template Toolkit by punch_card_don
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |