Improving Flexibility with Multiple Templates

As we’ve learned, a stylesheet is a set of rules. When you use only a single-root template, your stylesheet has, accordingly, only a single rule: “When you see the root of the source document, do everything inside this!”

As we’ll learn in this section, this strategy has pros and cons similar to those of adopting an “everything in a single main( ) method” coding style in Java:

public class doit {
  public static void main( ) (String[] args) {
    // When this program runs, do everything inside this!
  }
}

Developers learning Java find it easy to start with this simple approach, but they quickly find themselves writing repetitive code that would be nice to factor into helper methods. When this occurs, they would like to stand on the shoulders of other developers by extending others’ existing work, overriding just the methods that need to behave differently.

We’ll see that there is a nice conceptual analogy between methods in Java classes and templates in XSLT stylesheets. In Java, methods are both the unit of behavior and the unit of overriding. If you write a class with all of the programming logic in a single main( ) method, then someone extending your class can only override that single main( ) method. This means they have to rewrite all the logic just to change one small behavioral aspect. The more effectively a class’s methods are logically factored to represent the set of subtasks the class must perform, the easier it is to reuse a single ...

Get Building Oracle XML Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.