doy / text-handlebars

http://handlebarsjs.com/ for Text::Xslate
http://metacpan.org/release/Text-Handlebars
6 stars 9 forks source link

Iterate through keys? #5

Closed nowox closed 9 years ago

nowox commented 9 years ago

I am just trying Text::Handlebars and I still did not found how to iterate through the keys of an array.

 my $h = { data => {foo => 42; bar => 43} };
 my $template = '{{#each data}}{{.}}{{/each}}';

Perhaps this feature is not available yet.

However I can read from here than this should be possible:

 {{#each myObject}}
     Key: {{@key}} Value = {{this}}
 {{/each}}

Any clues?

doy commented 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!