If you've ever written an ASP page that sends an email or prints to a printer, you know
what a pain it can be to format the plain text that these tasks require. Your ASP code
usually ends up looking pretty ugly as a result and it usually takes a few tries to get
things looking the way you want. What if there was a way you could do the formatting
in a separate stand alone template file and then replace placeholders in that file with
the values from your script? Well... you can!
The Problem
I'm sure we've probably all written code like this at one point or another:
Well fine, but my point is that neither one is all that fun to write and they're even worse when you
need to try and change the formatting. And these are very short and simple examples. Back in my consulting
days there were times when I'd come across pages of this type of thing.
The Idea
The plan is to write a script that will read a template file off the file system and replace placeholders in that
file with their corresponding values. This not only allows for much more complex formatting, it also makes changing
the formatting as easy as changing the template file. Additionally, there's no reason you can't have one script use
multiple template files for different situations. You can think of it as almost like using different XSL stylesheets
with an XML document. The data is the same, but it's presentation can be totally different.
And speaking of XML, while I've been discussing using this technique for plain text things like email, there's nothing
to prevent you from using it in other scenarios... like with XML or HTML. Just change the template file and
you've got whatever format you need.
The Code
The code itself is pretty straight forward once you get the idea so I won't spend much time discussing it.
The script simply opens the template file, reads its contents into a string and then replaces the placeholders
with values from the script. I've used words in curly brackets (ie. { }) for placeholders in this sample
but you can use whatever you like.
template.asp
<%@ Language="VBScript" %>
<% Option Explicit %>
<html>
<head>
<title>ASP 101's Template File Sample</title>
</head>
<body>
<%
Dim objFSO
Dim objTemplateFile
Dim strTemplateText
Dim strTextToDisplay
' Read in our template from a file. I've included a couple sample templates.
' Try changing default.txt to asp101.txt. And there's really no reason your
' template files have to be plain text... HTML, XML, and other text-based
' formats all work just as well if you've got the need to use them.
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objTemplateFile = objFSO.OpenTextFile(Server.MapPath("default.txt"))
strTemplateText = objTemplateFile.ReadAll
objTemplateFile.Close
Set objTemplateFile = NothingSet objFSO = Nothing
' Replace placeholders with whatever values they should have.
' Naturally these would be pulled from a web form, database, or somewhere
' like that, but for simplicity, I'm just putting some sample values in so
' you can see how it works.
strTextToDisplay = strTemplateText
strTextToDisplay = Replace(strTextToDisplay, "{name}", "John Peterson")
strTextToDisplay = Replace(strTextToDisplay, "{company}", "Jupitermedia")
strTextToDisplay = Replace(strTextToDisplay, "{email}", "john@asp101.com")
strTextToDisplay = Replace(strTextToDisplay, "{url}", "http://www.asp101.com/")
strTextToDisplay = Replace(strTextToDisplay, "{phone}", "000-000-0000")
strTextToDisplay = Replace(strTextToDisplay, "{comments}", _
"This is a really cool idea." _
& " I don't know why everyone doesn't do this.")
strTextToDisplay = Replace(strTextToDisplay, "{timestamp}", Now())
' Display the resulting text. Again... you'd probably want to be emailing
' this or doing something exciting with the pretty results... but for
' illustration, I'll just display them in the browser.
Response.Write "<pre>" & vbCrLf
Response.Write strTextToDisplay
Response.Write "</pre>" & vbCrLf
%>
</body>
</html>
Sample Template Files
I've included a couple of sample template files in the zip to illustrate the concept.
Here are their listings so you can see what they look like:
default.txt
Name: {name}
Company: {company}
Email: {email}
Web Site: {url}
Phone: {phone}
Comments:
{comments}
Sent at: {timestamp}
asp101.txt
A SSSS PPPPP 1 0000 1
A A S P P 1 0 0 1
AAAAA SSSS PPPPP 1 0 0 1
A A S P 1 0 0 1
A A SSSS P 1 0000 1
==================================================================
Received: {timestamp}
==================================================================
From: {name}
Company: {company}
Email: {email}
URL: {url}
Phone: {phone}
Message:
{comments}
Download
You can download the script and sample template files in zip file format from here:
template.zip (1.5 KB).
Update: It's Really Not Just for Text Files
While the template method works great for email and and other plain text based formats,
as I mentioned above, there's no reason you can't use it for other file types as well. For example,
I was recently working on a project where the client was moving an Excel-based worksheet to a
web-based application. The problem was that the end users had really gotten to like the look
and feel of the Excel file format and very often were printing out the worksheet and
using the hard copy. That meant that although the client wanted to put the functionality on
the web, they also wanted to keep the same look and feel as much as possible.
After about 5 minutes of trying to mimic the Excel sheet in HTML, I started thinking
that there had to be a better way. Then it hit me... Excel will export to HTML.
Now granted, Excel generates bloated and ugly HTML and we all know it, but the client was
standardized on IE and the application was exclusively for internal use. Anytime
the worksheets went outside the company they were inevitably faxed or mailed. So, while I
personally hate the idea of ugly markup, in this case it was the lesser evil and gave the
client the result they wanted... a web page that looked exactly like their existing Excel sheet.
Now obviously I can't give you the actual client's worksheet so I've recreated a similar generic
Excel document for illustration purposes. Notice that wherever I want data to be placed dynamically
I've typed the placeholders into the sheet from within Excel.
Then I simply do a "File -> Save as Web Page..." and give the HTML file a name:
and Excel generates my HTML template file for me:
Now all that's left to do is to specify this file as the templete in the script above and insert
the values for the placeholders in the template. I'm inserting just name, date, phone, and email to
illustrate, but the assumption here is that all the values that you've inserted placeholders for
would come from your script. Calculating the values is unfortunately up to you.
SampleWorksheet.asp
<%@ Language="VBScript" %>
<% Option Explicit %>
<%
Dim objFSO
Dim objTemplateFile
Dim strTemplateText
Dim strTextToDisplay
' Read in our template from a file. I've included a couple sample templates.
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objTemplateFile = objFSO.OpenTextFile(Server.MapPath("SampleWorksheet.html"))
strTemplateText = objTemplateFile.ReadAll
objTemplateFile.Close
Set objTemplateFile = NothingSet objFSO = Nothing
' Replace placeholders with whatever values they should have.
strTextToDisplay = strTemplateText
strTextToDisplay = Replace(strTextToDisplay, "{name}", "John Peterson")
strTextToDisplay = Replace(strTextToDisplay, "{email}", "john@asp101.com")
strTextToDisplay = Replace(strTextToDisplay, "{phone}", "000-000-0000")
strTextToDisplay = Replace(strTextToDisplay, "{timestamp}", "July 10, 2007")
' Display the results.
Response.Write strTextToDisplay
%>
Notice that I've removed all the HTML from the processing file since the
template is a complete HTML file on its own.
And now the big reveal... the final web page with data from our script that looks (and prints)
just like the Excel sheet because we let Excel do the template generation for us:
Now eveyone's happy... I didn't have to spend hours designing an HTML file to look like the
Excel sheet and the client has a web page that looks like they wanted it to look.
The only scary thing is all the ugly HTML that is conveniently tucked away in the template
file which hopefully you'll never have to open.