The template content builder uses a separate component to insert generated nodes into the content tree. This is done when inserting the nodes when they are first created as well as when a new result is available. This additional component is called the sort service. It is responsible for determining where to insert nodes into the XUL document. Since the component is called the 'sort service' it is also used to sort the generated results. Since an RDF graph doesn't specify any order to results -- unless the items are in an RDF Seq -- the template builder will handle the results in any order. You may have noticed in the examples that results that are not in a Seq are not output in any particular order.

The sort service may be used to order the results in some particular order, generally, ascending or descending based on the value of some predicate pointing out of the result node. The sort service also supports a third sort order, natural order, which is the default. It causes items to appear without any extra sorting in the order they are added. However, if the results are items in a Seq they will appear in the order listed in the Seq. For instance, the photos are listed in the same order in this example as they appear in the Seq in the datasource.

This method of sorting a Seq works best for simple rule conditions since it is obvious how the starting ref relates to the end member results (they are just the children), or for extended syntax rules that follow a similar pattern. For more complex rules, this natural sorting will not work, because the sort service assumes that the starting ref resource is the container and the end results are the children. In this case, the natural order of the results will just be the order that the template builder generates the results.

For ascending or descending sorts, this doesn't matter, since it will ignore whether results are containers and just sort by a value, alphabetically or numerically depending on the type of data.

The sort service only applies to content builders. The tree builder uses a different and much simpler means of sorting since there is no content to insert. It supports the same three types of sorting, natural, ascending or descending. In the latter two sort types, the tree builder sorts by the value in a column. For instance, if the photos were displayed in a two column tree showing the title and description, you could sort by either title or description. The user can change the sort column and direction by clicking the column headers, however, you can programmatically change the sort as well.

Next, we'll look at some examples of tree sorting. We'll examine trees first because they are much simpler to handle, and you will usually want to support sorting on trees.