Search code examples
perltemplate-toolkit

Display array in multi-column table using template tookit?


I have an array of phone numbers. I want to display these numbers in a table, 5 numbers per row. Can I do this in Template Toolkit without modifying my data structure?


Solution

  • You can use the plugin Template::Plugin::Table:

    [% USE table(phone_numbers, cols=5) %]
    
    [% FOREACH row IN table.rows %]
       [% FOREACH item IN row %]
          [% item %]
       [% END %]
    [% END %]
    

    phone_numbers is a reference to the phone number array which should be passed to Template Toolkit. Example:

    ...
    $data->{phone_numbers} = \@phone_numbers;
    
    $template->process('example.tmpl', $data) 
       || die "Template processing failed: ", $template->error(), "\n";