Skip to main content

Build custom templates for your data-driven Web sites

Create custom templates and skins

Ken Ramirez (ken.ramirez@axsystechgroup.com), Founder, Axsys Technology Group
Ken Ramirez is the founder of Axsys Technology Group, which provides hosting and custom Web site development through Axsys Hosting. Ken also works with small business owners who are looking for inexpensive Web site solutions through his BuildMySiteTonight.com Web site. His company specializes in PHP, MySql, Linux, XHTML/CSS, Adobe Flash, E-commerce solutions, and content management solutions. You can reach Ken at AxsysHosting.BlogSpot.com.

Summary:  Most developers dread dealing with HTML tables and cells to build their Web sites. For one thing, tables make it difficult to modify the site later or to change its appearance. Discover some basic techniques for writing Web sites that you can later re-skin by using templates during the site's initial creation. Also, learn why you should use data-driven techniques for your own Web sites.

Date:  22 Apr 2008
Level:  Intermediate PDF:  A4 and Letter (196KB | 18 pages)Get Adobe® Reader®
Activity:  669 views
Comments:  

One of the worst things a back-end developer has to contend with is HTML. In my career, I haven't met too many developers who enjoy writing or modifying the front-end code, which is absolutely necessary for presenting any kind of output to your Web site's visitors. However difficult or tedious it may be, it is, nonetheless, sometimes necessary. Most developers feel comfortable writing the middle-tier and database code but loathe dealing with front-end formatting, tables, and the list of tags, attributes, and styles that come along when dealing with HTML and its handsome cousin, CSS.

Frequently used acronyms

  • CSS: Cascading Style Sheets
  • HTML: Hypertext Markup Language
  • XML: Extensible Markup Language
  • XHTML: Extensible Hypertext Markup Language
  • XSL: Extensible Stylesheet Language

Even if you manage to tango with HTML at a successful level, most Web sites are entirely rewritten each time they need a new look and feel. To re-skin the site, however, is just too expensive and confusing most of the time—especially if the site's code has sat untouched for a while.

To make matters worse, with the advent of Web 2.0, many developers are confused about the proper approach to development. We know that part of the equation should be to think ahead (providing a solid design and architecture), but quality is usually compromised because of budget and deadline concerns. Unless you or your clients aren't concerned about having to redo the Web site from scratch the next time the site's appearance must be upgraded, you'll need to ensure that the code is clean, optimized, and uses strict coding techniques on the front end to build solid foundations that lend themselves to Web 2.0, including Asynchronous JavaScript™ + XML (Ajax).

Additionally, making content changes would be easier if you develop a Web site that has a data-driven component to it—one for which you can modify the content of the Web site using a Web-based approach rather than having to modify the actual pages themselves each time you want to augment the site's content. This article discusses these concepts as well as problem resolution.

Note: The source code used in this article is available in the Resources section below.

The typical architectural approach

This article discusses the concepts behind writing clean, optimized, and strict code with particular attention to using these techniques in the development of templates for Web sites. First, I discuss these concepts a bit further, then show how you can put them into action to build Web sites using templates, which are sometimes referred to as skins.

As Figure 1 shows, a Web site is often broken up into several interconnecting pieces, such as a database holding your customer's valuable data and your site's configuration information. The database is often accessed by components or objects that execute on the server and are called by other layers of code, often referred to as the middle tier. The middle tier is commonly the first stop along the path of a request from the browser. This request is typically what occurs when users click an action, triggering the request.


Figure 1. A typical architecture
A typical architecture

After the server processes the request, the response (which includes both text and graphics) can return to the browser in any of several ways, including:

  • Plain XML
  • XHTML
  • HTML
  • XML/XSL combination
  • XHTML/CSS combination

Improperly formatting content

The most common approach to formatting data and images even today is to structure and organize the returning content in HTML tables. Many times, you even see that the data is formatted using tags and inline styling within the returning HTML. Typical code might resemble Listing 1.


Listing 1. Example of bad content formatting
                
<table width="703" height="100%"  border="0" cellpadding="0" cellspacing="0">
	<tr>
		<td  colspan="5">&nbsp;</td>
	</tr>
	<tr>
		<td>&nbsp;</td>
		<td align="right">
			<img  src="images/top_left_border.jpg"
		width="40"  height="26" /></td>
		<td  width="100%" height="26"  background="images/top_border.jpg" />
		<td  align="left">
			<img src="images/top_right_border.jpg"
		width="36" height="26" /></td>
		<td style="line-height:20px;  color: red">
			<strong>
				This is some content that will be shown to site visitors
			</strong></td>
	</tr>

This code breaks every rule and best practice for HTML coding. For one, it makes it difficult to maintain and further modify this file in the future, because you have to reacquaint yourself with the layout and styling each time you open it, resulting in wasted time. Wasted time equates to unhappy clients, because you're more than likely on a client's payroll each time you're producing or modifying code.

Second, you'll never be able to re-skin this code to provide a different look and feel for the site. If you attempt to do so, it's guaranteed to be expensive at the very least.

Formatting content properly

A better approach is to move all the formatting from this file to a CSS file. Listing 2 shows an HTML file that uses strict XHTML coding techniques. If you study this code closely, you'll probably think it resembles XML more than HTML (and you'd be correct).


Listing 2. A better approach to XHTML content
                
<body>
  <div id="container">
    <div  id="header">
      <div  id="logo"><span></span></div>
        <div  id="search_area">
        <?php  mosLoadModules( 'user4' ); ?>
      </div>

      <div  id="flash_banner">
        <?php  mosLoadModules( 'user3' ); ?>
      </div>
    </div>

    <div  id="menu_bar">
      <?php  mosLoadModules( 'user5' ); ?>
    </div>

    <div  id="left_sidebar">
      <?php  mosLoadModules( 'left' ); ?>
    </div>

    <div id="content_top">
      <?php  mosMainBody(); ?>
    </div>

    <div  id="footer_area">
      <div  id="footer_left_corner">
        <span></span>
      </div>

      <div  id="footer_menu">
        <?php  mosLoadModules( 'user6' ); ?>
      </div>

      <div  id="footer_right_corner">
        <span></span>
      </div>
    </div>

  </div>

  <div id="signature">
    <span>Designed  and Powered By
      <a  href="http://www.axsyshosting.com" target="_blank">Axsys  Hosting</a>
    </span>
  </div>

</body>

The example in Listing 2 is based on a template that I wrote for one of my clients (I'll get to templates shortly) for a Joomla-based site. Listing 3 provides an example of a CSS file that you can use to transform the above code into a thing of beauty.


Listing 3. A CSS file provides formatting for your XHTML file
                
body {
    text-align:  center; /* center hack */
    margin: 0px;
    font-family:  verdana;
  }

html {
  background:  #102a43 url(../images/background.jpg) 0 0 repeat-x;
  }

#container {
  display: block;
  background-color:  #e7eaf2;
  background-attachment:scroll;
  width: 849px;
  margin: 0 auto;
  text-align:  left;
  overflow:hidden;
  }

/* Header, Logo, Search Area, Cart Info, and Flash Banner */
#header {
  float: left;
  width: 849px;
  height: 242px;
  margin: 0px;
  padding: 0px;
  }

#logo {
  float: left;
  background:  #8f1b1b url(../images/site_logo.jpg)  no-repeat top left;
  width: 358px;
  height: 242px;
  margin: 0px;
  padding: 0px;
  }

/* Search Area */
#search_area {
  background:  #1a212c url(../images/search_box_bkgd.jpg) no-repeat top left;
  float: left;
  width: 263px;
  height: 32px;
  margin: 0px;
  padding: 0px;
  }

#search_area input.inputbox {
  float: left;
  margin: 0px;
  margin-top: 6px;
  margin-left:  15px;
  overflow:visible;
  height:15px;
  width:210px;
  padding: 0px;
  }

#flash_banner {
  float: left;
  background:  #bbc2d2 no-repeat top left;
  width: 491px;
  height: 170px;
  margin: 0px;
  padding: 0px;
  overflow:hidden;
  border:none;
  text-align:left;
  }

/* Menu Bar */
#menu_bar {
  float: left;
  background:  url(../images/menu_bar.jpg) 0 0 repeat-x;
  height: 33px;
  }

Let me be the first to say that this technique isn't new. It has been around for a while now but is often misunderstood or thought of as the "bells and whistles" that you'll get to if time permits. In fact, this technique is the topic of an entire Web site—Zen Garden—dedicated to providing only one page that has been re-skinned by a good handful of developers who have accepted CSS as the only method for formatting an XHTML page. Look at the number of independent CSS files that have been developed and donated by developers from all over the world. These are fine examples of re-skinning a Web site easily and elegantly. When you understand this concept, you can easily use it to produce templates for your own sites.

Achieving your look without tables

All these designs have one thing in common: They all achieve the look and layout they want without those nasty tables that most developers rely on to achieve their Web site's layout. Since the pre-dawn of HTML, everyone has said that you should only use tables when you actually need a set of rows and columns in which to draw data that actually needs to resemble a spreadsheet. Otherwise, consider an alternative, such as CSS positioning or floating blocks.

Developing templates

Using this technique, you can not only change the font family, sizes, and colors of your text, but you can also change the placement and layout of content and—in some cases—even change the content from plain text to astonishing graphics. You can use this technique for all kinds of sites, as well (a variety of frameworks—everything from a Microsoft® .NET application to a LAMP application to a Java™ application).

Let me give you an example. I'm currently working with a client that wants the main index page to provide a set of "look-n-feel" choices from which the site's visitors can choose. The selection determines the site's appearance (for example, placement, colors, fonts). By providing this value to the incoming home page, I ensure that the home page brings back the correct CSS file on the fly. You can do this in any language, but for demonstration purposes, I show you how to achieve it using PHP. You can access and view a working example of this code at the link listed in the Resources section of this article.

First, you need an index file that can be called upon to display the color (or template) choices. The following code does just that:

<body>
<h1>Template Article
</h1>
<ol>
  <li><a  href="home-page.php?template=blue">Blue  Appearance</a></li>
  <li><a  href="home-page.php?template=red">Red  Appearance</a></li>
  <li><a  href="home-page.php?template=green">Green  Appearance</a></li>
</ol>
</body>

As you can see, the anchors provide complete links that pass a parameter value to the home page. This value is named template, but the name is arbitrary, and you can call it anything you like. Inside the home page, you need to retrieve the template value, store it, and use it to summon the request template (or CSS) file. Here's how you achieve this:

<?php
  $template =  $_GET["template"];
?>
<link href="<?php echo $template; ?>.css"  rel="stylesheet" type="text/css" />

The template value becomes the name of the CSS file that you want to use for formatting the content. You're essentially treating the response as a funnel that combines the content (and any graphics) with the styling and formatting. Figure 2 provides a conceptual demonstration that ties these concepts together.


Figure 2. Demonstration of formatted XHTML
Formatted XHTML

Now, we'll look at the content you want to format. Listing 4 provides an XHTML file that has no styling. It only provides elements that can be completely formatted using CSS.


Listing 4. The XHTML file
                
<body>
<h1>Template Article</h1>

<div id="paragraph1">As a developer, one of the worst things you have to contend with
on a daily basis is HTML. In my career, I haven't met too many developers who enjoy
writing or modifying the front-end code, which is absolutely necessary in order to
present any kind of output to your website's visitors. However difficult it may be, it
is nonetheless necessary. Most developers feel comfortable writing the middle tier
and database code, but loathe to deal with front-end formatting, tables, and the list
of tags, attributes, and styles that come along when dealing with HTML and its handsome
cousin, CSS.</div>

<div id="paragraph2">Even if you manage to tango with HTML at a successful level, most
websites are entirely rewritten each time a new look and feel is desired. To reskin the
site is just too expensive and confusing most of the time, especially if the site's
code has sat untouched for awhile.</div>

<p><a href="index.html">return to index page</a></p>

</body>

This file contains only elements that provide structure to the XHTML, allowing you to easily address those pieces using CSS. The rule is that you should have as much division within your XHTML as necessary to properly rearrange and style the content. In this case, you're using a heading and two <div> tags as well as a link. Because you already saw how to select the appropriate CSS file using PHP, take a look at the output that this technique produced, as shown in Figure 3.


Figure 3. Same home page using different templates
Same home page using different templates

As you can see, even though the same home page is called, it appears significantly different from each link. This transformation is all the result of the power of CSS and some handy coding up front before any output is sent back to the browser. The key to making this technique work is the <style> tag, which is manipulated on the fly before being sent back to the browser for further processing. Listing 5 shows the style sheet for the blue styling, Listing 6 shows the style sheet for the red treatment, and Listing 7 shows the style sheet for the green.


Listing 5. CSS file providing the blue look and feel
                
body {
	background-color:  #33CCFF;
}

a {
	display: block;
	float:right;
	color: blue;
}

h1 {
	font-family:  Verdana, Arial, Helvetica, sans-serif;
	font-size:    18px;
	color:        #000099;
}

#paragraph1 {
	font-family:  "Times New Roman", Times, serif;
	font-size:    12px;
	color:        #0000FF;
}

#paragraph2 {
	margin:       20px;
	font-family:  Geneva, Arial, Helvetica, sans-serif;
	font-size:    14px;
	color:        #3366CC;
	text-decoration:  underline;
}


Listing 6. CSS file for achieving the red appearance
                
body {
	background-color: #FFCCCC;
}

a {
	display: block;
	float:right;
	color: red;
}

h1 {
	float: right;
	font-family: Georgia, "Times New Roman", Times, serif;
	font-size:   22px;
	color:       #FF0000;
}

#paragraph1 {
	margin:      60px;
	font-family: "Century Gothic", Verdana, Arial, Tahoma;
	font-size:   9px;
	color:       #FF0033;
}

#paragraph2 {
	font-family: Geneva, Arial, Helvetica, sans-serif;
	font-size:   10px;
	color:		 #CC0033;
	text-transform: lowercase;
	font-style:  italic;
}


Listing 7. CSS file for achieving the green formatting
                
body {
	background-color: #CCFFCC;
}

a {
	display: block;
	float:left;
	color: green;
}

h1 {
	position: absolute;
	left: 80px;
	top: 275px;
	font-family: Georgia, "Times New Roman", Times, serif;
	font-size:   22px;
	color: #006600;
}

#paragraph1 {
	float: right;
	margin: 30px;
	font-family: "Courier New", Courier, monospace;
	font-size:   11px;
	color: #00CC66;
}

#paragraph2 {
	float: left;
	position:absolute;
	display: block;
	left: 0px;
	top: 0px;
	margin: 10px;
	font-family: Geneva, Arial, Helvetica, sans-serif;
	font-size:  11px;
	color:  #66CC99;
	font-style: italic;
}

The main home page contains an <h1> section, two parameters wrapped with <div> tags, and an <a> tag. All these elements plus the body have been modified using CSS.

Notice that there are several differences among the various style sheets. Some of these differences change the layout of the elements, while others modify the colors, font, text style, and background.

The other thing you should keep in mind when developing templates for your own sites is that you should create folder hierarchies that lend themselves well to maintaining all the pieces of your template together. For example, if your template requires graphic images, place them in an images folder within your template. See Figure 4 for an example of a folder hierarchy.


Figure 4. Folder hierarchy for templates
Folder hierarchy for templates

Adding data-driven functionality

Now that you've seen how to create templates for your Web sites, we'll add the final piece to complete this article: the data-driven portion. The idea behind creating data-driven Web sites requires that you build an administrative module for your sites. Many clients won't see the value in paying for something like this until it becomes necessary for them to make changes to their Web site. When the time comes, they'll need to enlist your help again just to make simple content changes. Over time, their ownership cost will increase. This is good for you but bad for them.

I often explain this to my own clients and convince them to let me build an administrative piece (also known as an admin console) for their Web site, then provide them with the proper training to operate the admin console themselves. This empowers them to make their own minor content modifications without having to wait until I become available to handle their changes. In the end, it's less expensive to pay for an admin console up front than to pay for further content changes throughout the lifespan of a Web site.

An admin console can be as simple as a few pages for performing administrative work or as complicated as an entire Web site filled with features and functionality to provide someone the ability to customize the content and sometimes the images that a Web site offers. Figure 5 provides an illustration of what a simple admin console used to handle the data for your Template Article Web site might look like.


Figure 5. Admin Web page
Admin web page

I've created fields for each section in the final Web site. If I modify the values in these fields and submit the form, the data is stored on the server for later access by the actual Web site. Furthermore, it doesn't matter what my storage medium is. It can be a simple file (as I've used in this example), a database, an XML file, or anything else you might need to use for your own Web site.

I'll show you how I created the code for this admin Web page. Later, you'll see the code behind the Submit button. Again, for demonstration purposes, I use PHP to create the content of this page, which is shown in Listing 8.


Listing 8. My admin page
                
<?php
	require_once("config.php");
?>

<body>
<h1>Template Article - Admin</h1>
<form id="form" name="form" method="post" action="admin.php">
	<input type="hidden" name="store" value="true" />
	<label>Heading:
		<input type="text" name="HEADING" id="heading" value="<?php echo
 HEADING; ?>"/>
	</label>

	<p>&nbsp;</p>
		<label>Paragraph 1:
			<textarea name="PARAGRAPH1" id="paragraph1" cols="45" rows="5">
				<?php echo PARAGRAPH1; ?>
			</textarea>
		</label>

	<p>
		<label>Paragraph 2
			<textarea name="PARAGRAPH2" id="paragraph2" cols="45" rows="5">
				<?php echo PARAGRAPH2; ?>
			</textarea>
		</label>
	</p>

	<p>
		<label>
			<input type="submit" name="button" id="button" value="Submit" />
		</label>

		<label>
			<input type="reset" name="button2" id="button2" value="Reset" />
		</label>
	</p>

</form>
</body>

To access a live version of this page, see Resources for a link.

The code begins by first including a file containing the definitions of the <heading>, <paragraph>, and <paragraph>. Again, the source of this data can be just about anything you can imagine. For simplicity, I chose to use a PHP file that contains the data. This file will be recreated each time I submit the posted data back to the server. The <form> tag contains an address that points back to the same script. I can do this because the top of this file contains an if statement that checks for the existence of the hidden input field named store, which is always set to True. Listing 9 shows the remaining code of the PHP file, which is actually at the top of the file.


Listing 9. Remaining portion of the admin page
                
<?php
    if($_POST['store'] == 'true') {
      $config =  "<?php\n";
      foreach( $_POST  as $key => $value ) {
         $config  .= "define (\"$key\", \"$value\");\n";
    }
    $config .=  "?>";

    if ($fp =  fopen("config.php", "w")) {
        fputs($fp,  $config, strlen($config));
        fclose  ($fp);
    }
    else {
        echo  'Problem occurred while trying to save data into config.php';
        return  false;
    }
}
?>

Now, I need to make a few modifications to the home page to use the data stored in config.php. Listing 10 provides the new code used in the home page.


Listing 10. New home page using the data-driven approach
                
<body>
  <h1><?php echo HEADING; ?></h1>
  <div id="paragraph1"><?php echo PARAGRAPH1; ?></div>
  <div id="paragraph2"><?php echo PARAGRAPH2; ?></div>
  <p><a href="index.html">return to index page</a></p>
</body>

The first thing that should immediately strike you about this page is that it has shrunk considerably. Instead of the data being placed in the XHTML file directly, it is kept elsewhere and brought into the page using code fragments. Now, the XHTML page has become a place to integrate the various pieces of the site. It contains the sections of the page without any actual content or styling.

For completeness, look at the config.php file that maintains this data. This file is shown in Listing 11.


Listing 11. config.php
                
<?php
define ("HEADING", "Template Article");

define ("PARAGRAPH1", "As a developer, one of the worst things you have to contend
with on a daily basis is HTML. In my career, I haven't met too many developers that enjoy
writing or modifying the front-end code, which is absolutely necessary in order to
present any kind of output to your website's visitors. However difficult it may be, it is
nonetheless necessary. Most developers feel comfortable writing the middle tier and
database code, but loathe to deal with front-end formatting, tables, and the list of
tags, attributes, and styles that come along when dealing with HTML and its handsome
cousin, CSS.");

define ("PARAGRAPH2", "Even if you manage to tango with HTML at a successful level,
most websites are entirely rewritten each time a new look and feel is desired. To reskin
the site is just too expensive and confusing most of the time, especially if the site's
code has sat untouched for a while.");
?>

As you might imagine, the configuration file (or database, if you choose to keep it there) can be used for just about anything your Web site needs to do. You can not only maintain the language information (such as titles and paragraphs), but you can also maintain images, formatting, styling, and so on. The possibilities are endless. And based on a configuration value, you can change the site to support different foreign languages as well.

Summary

Web site developers need to consider alternatives to laying out and formatting their Web sites. It has become too difficult and expensive to continue using inline styling and tables for creating Web pages. If you plan ahead, you can actually build Web sites that lend themselves well to a template or re-skinning systems.

Several technologies exist today that assist developers in achieving a template-based foundation. For example, PHP has a popular one named Smarty Template Engine, which I really like (see Resources). Other languages have similar technologies. The best part of using a template-based system for your Web sites (especially those that will be publicly accessible) is that you can provide the content and back-end functionality, and someone else can provide the format and styling. Better yet, if you work with a team of designers, you can work together without stepping all over each others' toes, because you can truly separate the pieces of your Web site into various files, which funnel together at run time.

Adding a data-driven element to this formula makes your Web sites even more flexible, allowing non-technical personnel or the Web site's owner to make content (both text and graphics) changes to the site. This is, after all, the basis for most content management systems.


Resources

Learn

Get products and technologies

About the author

Ken Ramirez is the founder of Axsys Technology Group, which provides hosting and custom Web site development through Axsys Hosting. Ken also works with small business owners who are looking for inexpensive Web site solutions through his BuildMySiteTonight.com Web site. His company specializes in PHP, MySql, Linux, XHTML/CSS, Adobe Flash, E-commerce solutions, and content management solutions. You can reach Ken at AxsysHosting.BlogSpot.com.

Comments



Trademarks

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=302408
ArticleTitle=Build custom templates for your data-driven Web sites
publish-date=04222008
author1-email=ken.ramirez@axsystechgroup.com
author1-email-cc=

My developerWorks community

Special offers