Search code examples
htmlarraysperlcheckboxtemplate-toolkit

Using Template Toolkit to tick a checkbox without using multiple loops


I'm using Template Toolkit and perl to generate a web page. I have an array with ID numbers in it that toggle checkboxes on and off, if that value exists in the array. I was wondering if there is a more efficient way to do set a group of checkboxes on and off on page load. There is some previous code and it feels sluggish to load before I got it. I don't want to add any more to the wait time.

This works:

<label for="checkFedGround">
    <input type="checkbox" name="Shipping" id="checkFedGround" value="11"
        [% FOREACH ShippingID IN data.ShippingID %]
            [% IF ShippingID == 11 %] checked="checked" 
            [% END %]
        [% END %]
     enabled />             
        FedEx Ground
</label>

The problem with this is it would have to do the FOREACH loop for each of my shipping types. Seems to me there would be a lot of unnecessary processing. So let's say there are 30 checkboxes and 10 IDs in the array. That means the FOREACH would loop through 10 times for each checkbox just to validate a single ID.

I've been trying to use Template Toolkit::EXIST and similar methods to check if the ID is in an array once, but it's not working the way I want it to.

This does NOT work: This ticks the checkbox for values that are not in scope.

<input type="checkbox" name="Shipping" id="checkFedGround" value="11" 
    [% IF (data.ShippingID(11)) %] checked="checked"
[% END %]               
enabled />
FedEx Ground

Does anyone know a better way to do this?

UPDATE/SOLUTION: Thanks for the advice. As suggested, I ended up using a hash to store the data. I also scrapped the idea of using static check boxes in favor of a select list that creates a sorted list. JQuery reads the value of selected lines/checkbox, processes the hash array and passes it to Perl.

<table> ...
    <td> <input type="checkbox" name="ShippingID" value="[% service.ShippingID %]"
        [% IF service.default %] checked="checked" [% END %]
    style="margin: 0px;" />
</td> </table>
....
<select id="ShippingMethodSelect">
    <option value="">Add Shipping Method...</option>
    [% FOREACH service IN data.Shipping %]
        <option value="[% service.ShippingID %]">[% service.description %]</option>
    [% END %]
</select> 

Solution

  • Then don't use an array, use a hash.

    $data->{ShippingIDs} = { map { $_ => 1 } @ShippingIDs };
    

    Then you can use

    <input type="checkbox" name="Shipping" id="checkFedGround" value="11" 
        [% IF data.ShippingID.11 %] checked="checked" [% END %]
        enabled />
    FedEx Ground