Search code examples
jsonperltemplate-toolkit

Template Toolkit - Display array by ID


I want to display a block of an array by the ID - can I do this using Template Toolkit or will it be in the Perl controller side? (I'm using Dancer & REST::Client to grab the JSON)

This is the JSON:

    {
        "user":
        [
            { 
            "id": 12345,
                "name": bob,
                "age": 22,
                "birth_place": "London"
            },
            { 
            "id": 12346,
                "name": amy,
                "age": 20,
                "birth_place": "London"
            }
        ]
    }

I'm getting the ID of the user in the controller so I can display the ID in the template with [% user.id %]. So I want to be able to basically do

1) If user id matches the id of one of the id's in the JSON

2) Display data from that block

Name: [% content.name %]
Age: [% content.age %]
Birth Place: [% content.birth_place %]

Any help? :)


Solution

  • If you need to check for multiple users, you really want a hash rather than an array.

    my $data = decode_json(...);
    my %data_by_userid = map { $_->{id} => $_ } @{ $data->{user} };
    

    Template parameters:

    data_by_userid => \%data_by_userid
    

    Then, you'd use

    [% user = data_by_userid.$id -%]
    [% IF user -%]
    Name: [% user.name %]
    Age: [% user.age %]
    Birth Place: [% user.birth_place %]
    [% END -%]
    

    If you only need one user in the template, just use

    my $data = decode_json(...);
    my ($user) = grep { $_->{id} == $id } @{ $data->{user} };
    

    Template parameters:

    user => $user
    

    Then, you'd use

    [% IF user -%]
    Name: [% user.name %]
    Age: [% user.age %]
    Birth Place: [% user.birth_place %]
    [% END -%]