Database Reference
In-Depth Information
$item_ref = [ map { defined ( $_ ) ? escapeHTML ( $_ ) : "" } @ { $item_ref } ];
print ol ( li ( $item_ref ));
Note two things about the li() function:
• It performs no HTML-encoding; you must do that yourself.
• It can handle a single value or an array of values. If you pass an array, pass it by
reference so that li() adds <li> and </li> tags to each array element, concatenates
them, and returns the resulting string. If you pass the array itself rather than a
reference, li() first concatenates the items, then adds a single set of tags around
the result, which is usually not what you want. This behavior is shared by several
other CGI.pm functions that can operate on single or multiple values. For example,
the table data td() function adds a single set of <td> and </td> tags if you pass it
a scalar or list. If you pass a list reference, it adds the tags to each item in the list.
The Ruby equivalent of the previous example looks like this:
# fetch items for list
stmt = "SELECT item FROM ingredient ORDER BY id"
items = dbh . select_all ( stmt )
list = cgi . ol {
items . collect { | item | cgi . li { CGI . escapeHTML ( item . to_s ) } }
}
Should You Intertwine or Decouple Row Fetching and
HTML Generation?
You may be able to get a script working most quickly by writing code that prints HTML
from query rows as you fetch them. There are, however, several advantages to separating
data retrieval from output production. The most obvious ones are that by using a utility
function to generate the HTML, you have to write the function only once, and you can
share it among scripts. There are other benefits as well:
• Functions that generate HTML structures can be used with data obtained from
other sources, not just from a database.
• The decoupled approach enables you to more easily construct page content in
memory, then print it when you're ready. For building pages that consist of several
components, this gives you more latitude to create them in the order that's most
convenient. (On the other hand, with very large result sets, this approach can entail
considerable memory use.)
• Decoupling row fetching and output generation provides more flexibility in the
types of output you produce. To generate an unordered list rather than an ordered
list, just call a different output function; the data collection phase need not change.
This is true even if you decide to use a different output language (XML rather than
 
Search WWH ::




Custom Search