I have a few suggestions for you.
1) Change your hash to:
$ref = {
123 => {
title => 'first title',
id => 'id1',
},
234 => {
title => 'the second title',
id => 'id2',
},
345 => {
title => 'the third title',
id => 'id3',
},
};
Then just do ref.keys.nsort in your FOREACH loop
[% FOREACH r = ref.keys.nsort %]
<a href="/program?id=[% ref.$r.id %]">[% ref.$r.title _ " " _ r %]</a>
[% END %]
2) Or if you can't change your hash.
Change this:
$vars = {
ref => $ref,
};
to:
$vars = {
ref => $ref,
sort_keys_by => sub{
my $hash = shift;
my $sort_field = shift;
return sort {
$hash->{$a}->{$sort_field} <=> $hash->{$b}->{$sort_field}
} keys %$hash
}
};
Then change your foreach to be:
[% FOREACH r = sort_keys_by(ref, 'number') %]
<a href="/program?id=[% r %]">[% ref.$r.title _ " " _ ref.$r.number %]</a>
[% END %]
3) Similar to 2. Add a virtual method to your hashes. Just add this above your
process call. (Note: You might need to add: 'use Template::Stash;') :
$Template::Stash::HASH_OPS->{ sort_keys_by } = sub {
my ($hash, $sort_field) = @_;
return sort {
$hash->{$a}->{$sort_field} <=> $hash->{$b}->{$sort_field}
} keys %$hash
};
then you can do:
[% FOREACH r = ref.sort_keys_by('number') %]
<a href="/program?id=[% r %]">[% ref.$r.title _ " " _ ref.$r.number %]</a>
[% END %]
Sorry, if there are errors in this, I wrote it up pretty quick. I think you
should be able to do what you want with it, though.
-- Josh
Octavian Rasnita wrote:
Hi,
I have a hash reference like:
$ref = {
id1 => {
title => 'first title',
number => 123,
},
id2 => {
title => 'the second title',
number => 234,
},
id3 => {
title => 'the third title',
number => 345,
},
};
And I want to print the values in a template, sorting the titles by
"number", in html links, something like:
$vars = {
ref => $ref,
};
$tt->process("file.html", $vars);
The file file.html:
[% FOREACH r = ref.keys %]
<a href="/program?id=[% r %]">[% ref.title _ " " _ ref.number %]</a>
[% END %]
But I want those links be sorted by the ref.number. Is it possible? Or I
need to create another array with the keys of the hash I want to sort in
order and then loop that array?
Thank you.
Teddy
_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates
!DSPAM:42b40fa7148758171910352!
_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates