For a recent project, we had to do some dynamic content replacement on a web page. We had to support a primitive version of IE (viz., Pocket IE for Windows Mobile 2003), so fancy DOM element creation and manipulation were out of the question — we were stuck with simply changing the value of the exposed innerHTML JavaScript attribute of <div>s, <span>s, etc.
Some of the dynamic content was relatively long (using tables, etc for layout), so rather than creating it using a long series of JavaScript string concatenations (with all necessary character escapes), we created <span>s that contained template HTML. For example:
<span id="template" style="display:none;">
<table>
<tr><th>Name</th><th>Value</th></tr>
<tr><td>{propertyName}</td><td>{propertyValue}</td></tr>
</table>
</span>
Then, we can get the template string:
var templateStr = template.innerHTML;
Notice that the template has a couple strings enclosed in curly braces. These are tokens that will be replaced by values from a JavaScript object. A simple JavaScript method takes care of this:
<script language="JavaScript">
function doTemplateReplacements (template, tokensObj)
{
var output = template;
for (var prop in tokensObj)
{
var re = new RegExp ("\{" + prop + "\}", "g");
output = output.replace (re, tokensObj[prop].toString());
}
return output;
}
</script>
Usage is pretty straightforward. Simply pass the template string and an object with properties matching the tokens in the template. Then, set the innerHTML of your “target” container to the dynamicContent string.
<span id="target"></span>
<script language="JavaScript">
var dynamicContent =
doTemplateReplacements (templateStr,
{ propertyName: "Cost",
propertyValue: "$100.00" });
target.innerHTML = dynamicContent;
</script>
The target <span>’s content becomes
<table>
<tr><th>Name</th><th>Value</th></tr>
<tr><td>Cost</td><td>$100.00</td></tr>
</table>
A while after devising this approach, I ran across the TrimPath JavaScript Templates library. This library supports this simple templating and a *lot* more. I haven’t actually used this library, but it’s interesting in that it implements a micro expression language for use in the templates. Might have been useful in the project, but I’m not sure if it would be 100% functional in Pocket IE.