Tuesday, May 22, 2018

Turning Apache SSI usage on its head.

Most people who talk about templating with Apache Server-side Includes scripting (SSI) have HTML pages pull in pieces of common code such as styles, headers, footers and so on, then hard code the content in the page. This technique certainly reduces the amount of code in each page. And, one can make some changes in a single place. In programming parlance, it modularizes the code. This approach has drawbacks, though.
  • Depending on what is pulled in, changing the structure of all the pages in the site may mean editing many files.
  • The content can't be presented in different ways for different purposes. It can't be reused.
So, what if we turn this concept on its head? What if the content calls the “page”, or more broadly the “template” rather than each page having content. What would that look like?

SSI can set variables. The variables can contain anything that is a string. The variables can be substituted for text just about anywhere, including in the URI in an SSI command.

What does that mean? It means that content can be put in a file that calls a “page” to display itself. The steps are:
  1. Set one or more variables with content.
  2. Call a template file, either a fixed one, or, and here's the beauty of it, one whose path is in a variable that was set before the content file was called.
  3. The template file puts the content variables in the appropriate places.
Why go to this trouble? Because the template file that’s called can be different depending on the desired output. One time it can be a complete HTML page. Another time it can be an HTML fragment such as a paragraph or a list element. Another time it can be an RSS feed item. Another time it can be Javascript variables. The same content. Only the template changes.

What's more, one template can be used for many pages, potentially an entire site. So, if the site structure or style changes, only one file has to be modified.

In some sense, this turns SSI into an object-oriented system, bringing it into the modern era of system architecture. The variables are object attributes and the template file is the method. What's more, the method can be anything. Unlike most OO languages, it doesn't have to be hard coded. (Although it could be by using #if conditional processing to choose among a fixed set of methods.)

Regardless, the possible uses of this technique are limited only by one’s imagination. The output can be anything that is deliverable in response to a Web request, even JSON. And, it can be driven by parameters in the URL that called it. (Apache SSI has access to the query string.) RESTful services anyone?

No comments:

Post a Comment

Comments are moderated.