## Implementing Data Sources

Templating System : Developer Guide : User Guide

Data sources are implemented in a Tcl script using regular Tcl variables, lists and arrays. The templating system includes a set of procedures to simplify the construction of data sources from relational database queries.

### The Structure of Data Sources

The templating system can manipulate four basic types of structures as data sources:

`onevalue` | A simple scalar, such as a user's first name or the total due on a purchase order.
`onelist` | A list of simple scalars.
`onerow` | A one-row data table, with values in one or more columns.
`multirow` | A multi-row, multi-column data table.

### `onevalue`

`onevalue` data sources are implemented simply by setting a Tcl variable:

`set name "Walter Cronkite"`

The `query` procedure may be used to set a onevalue data source based on a database query:

`query name onevalue "select name from users where user_id = 123"`

You can embed a `onevalue` data source in a template with simple variable substitution.

### `onerow`

`onerow` data sources are implemented as Tcl arrays:

`set name(first_name) Walter
set name(last_name) Cronkite`

The `query` procedure may be used as a convenient way to store the result of a one-row database query into an array:

    query name onerow "
      select
        first_name, last_name
      from
        users
      where
        user_id = 123"

You can embed references to column values of a `onerow` data source in a template with simple variable substitution.

### `onelist`

`onelist` data sources are implemented by creating a Tcl list:

    set names [list "Walter" "Fred" "Susy" "Frieda"]

The `query` procedure may be used to set a onelist data source based on a one-column database query:

`query name onevalue "select name from users"`

You can iterate over a `onelist` data source in a template with the list tag.

### `multirow`

`multirow` data sources are not represented by a single Tcl data structure. As such the templating system includes a special API for constructing and manipulating them.

    multirow create cars make model year
    multirow append cars "Toyota" "Camry" "1996"
    multirow append cars "Volvo" "960" "1995"

The `query` procedure may be used as a convenient way to store the result of a multi-row, multi-column database query into a `multirow` data source:

    query name multirow "
      select
        make, model, year
      from
        cars"

You can iterate over a `multirow` data source in a template with the multiple tag.

templating@arsdigita.com