"selected" in a loop

2000-11-04
2001-07-12
  • Dennis Laursen
    Dennis Laursen
    2000-11-04

    cool templaet-module, but i've run into a small problem....

    i'm building a couple of pages with dropdown-boxes, based on data from a database. I've used the <TMPL_LOOP> to build the dropdown-boxes, but what is the best way to mark one of them as "selected"?

    As i've understood, the TMPL_IF can only check boolean values? it could be cool if i were able to do <TMPL_IF NAME=[var-name] VALUE=[value to be checked with]> and the value of [var-name] would be checked agains the [value to be checked with]...if they match => true, if not => false.

    Have I missed something? or would you consider expanding the features of TMPL_IF?

    ./Dennis

     
    • I do it this way:
      <select>
      <TMPL_LOOP foo>
         <option value=<TMPL_VAR foo>> <TMPL_IF bar>selected</TMPL_IF>>
      </TMPL>
      </select>

      In Perl I have

      $dbq = "SELECT foo, (foo = $myfoo) AS bar FROM footable";

      ...

      my @loop;
      while ($row=$sth->fetchrow_hashref)
      {
        push @loop, $row;
      }

       
    • Why not simply append text to the variable you wish to put in the option-tag:

      <select>
      <TMPL_LOOP>
      <option value=<TMPL_VAR userid>><TMPL_VAR username>
      </TMPL>
      </select>

      and in perl:

      foreach(resultset foo)
      {
      $userid .= " selected " if ($selected);
      $loopvalues{userid} = $userid;
      $loopvalues{username} = $name;
      }

      ...but then again, avoiding unnecessary assignments (i.e. using _arrayref directly) is better for performance.