Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I find out if variable is an array using Template Toolkit?

I'm passing the results of a multi-select box to a page so that the selections can be shown on screen. As it's multi-select, the result can either be a scalar or an array reference. Is there a way of finding this out? I can't find anything online, but I thought there might be a .array or .array_ref token that could be used for validation. I'm using Template Toolkit, Perl and Dancer.

So here is what I've got for a scalar:

<% IF multitext %>
    Text: <% multitext %>
<% END %>

What I want is something like...

<% IF multitext %>
    <% IF multitext.array_ref %> <!-- whatever works! -->
        <% FOREACH text IN multitext %>
            Text: <% text %>
        <% END %>
    <% ELSE %>
        Text: <% multitext %>
    <% END %>
<% END %>
like image 414
dgBP Avatar asked Apr 26 '26 10:04

dgBP


1 Answers

If <%- multitext.0 -%> returns a non-zero value, it's an arrayref.

If <%- multitext.keys.size -%> returns a non-zero value, it's a hashref.

The way I usually handle it is to force it to be an array if it's a scalar, eg:

<%- SET items = multitext.0 ? multitext : [ multitext ];
    FOREACH item IN items;
        ...
    END; -%>
like image 92
RET Avatar answered May 04 '26 08:05

RET