Closed nowox closed 9 years ago
Sorry for the delay in answering! Handlebars doesn't have any built-in mechanisms for iterating over hashes, but you can provide this functionality pretty easily yourself by writing helpers. For instance:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use Text::Handlebars;
my $handlebars = Text::Handlebars->new(
helpers => {
keys => sub {
my ($context, $hash) = @_;
[ keys %$hash ]
},
values => sub {
my ($context, $hash) = @_;
[ values %$hash ]
},
kv => sub {
my ($context, $hash) = @_;
[ map { +{ k => $_, v => $hash->{$_} } } keys %$hash ]
},
}
);
say $handlebars->render_string(<<EOF, { h => { a => 1, b => 2 } })
keys:
{{#each keys h}}
{{.}}
{{/each}}
values:
{{#each values h}}
{{.}}
{{/each}}
kv:
{{#each kv h}}
{{k}}: {{v}}
{{/each}}
EOF
which outputs:
keys:
a
b
values:
1
2
kv:
a: 1
b: 2
Let me know if you have any other questions!
I am just trying
Text::Handlebars
and I still did not found how to iterate through the keys of an array.Perhaps this feature is not available yet.
However I can read from here than this should be possible:
Any clues?