To read the article online, visit http://www.4GuysFromRolla.com/webtech/010200-1.shtml

A JScript Port of the Perl/PHP FastTemplate Module

By Ludovico Magnocavallo


(heavily based on CDI's FastTemplate PHP3 class docs)


NAME

AspTemplate 0.1 - JScript extension for managing templates and performing variable interpolation.


SYNOPSIS

<%@ LANGUAGE=jscript %>
<!--#include file="ftemplate.asp"-->
	var tpl = new fasttemplate("c:\\inetpub\\asptemplate\\templates");
	tpl.define(
		{"main":"main.tpl","body":"body.tpl"}
	);
	tpl.assign("BODY", "un titolo");
	tpl.assign("TITLE", "titolo");
	tpl.assign({"BODY2":"body 2","BODY3":"body 3"});
	tpl.assign("SOMETEXT","del testo");
	tpl.parsetpl(
		"MAIN",
		["main", "body"]
	);
	tpl.fastprint("MAIN");
%>


DESCRIPTION

What is a template?

A template is a text file with variables in it. When a template is parsed, the variables are interpolated to text. (The text can be a few bytes or a few hundred kilobytes.) Here is a simple template with one variable ('{NAME}'):

Hello {NAME}.  How are you?

When are templates useful?

Templates are very useful for ASP programming, because adding HTML to your JScript code clutters your code and forces you to do any HTML modifications. By putting all of your HTML in seperate template files, you can let a graphic or interface designer change the look of your application without having to bug you, or let them muck around in your JScript code.

Why use AspTemplate?

Speed

AspTemplate parses with a single regular expression. It just does simple variable interpolation (i.e. there is no logic that you can add to templates - you keep the logic in the code).

Flexibility

The API is robust and flexible, and allows you to build very complex HTML documents/interfaces.

What are the steps to use AspTemplate?

The main steps are:

1. define
2. assign 
3. parse
4. FastPrint

These are outlined in detail in CORE METHODS below.


DOWNLOAD


You can get asptemplate from http://www.4GuysFromRolla.com/webtech/code/asptemplate.zip


CORE METHODS


define( Array( key,value pairs) )

The method define() maps a template filename to a (usually shorter) name;

	var tpl = new fasttemplate("c:\\inetpub\\asptemplate\\templates");
	tpl.define({"main":"main.tpl","body":"body.tpl"});
or (pre JScript V5)
	var tpl = new fasttemplate("c:\\inetpub\\asptemplate\\templates");
	var definearray = new Array();
	definearray["main"] = "main.tpl";
	definearray["body"] = "body.tpl";
	tpl.define(definearray);

This new name is the name that you will use to refer to the templates. Filenames should not appear in any place other than a define().

(Note: This is a required step! This may seem like an annoying extra step when you are dealing with a trivial example like the one above, but when you are dealing with dozens of templates, it is very handy to refer to templates with names that are indepandant of filenames.)

TIP: Since define() does not actually load the templates, it is faster and more legible to define all the templates with one call to define().


assign( (key,value pair) or ( Array(key value pairs) )

The method assign() assigns values for variables. In order for a variable in a template to be interpolated it must be assigned. There are two forms which have some important differences. The simple form, is to accept an array and copy all the key/value pairs into an array in AspTemplate. There is only one array in AspTemplate, so assigning a value for the same key will overwrite that key.

	tpl.assign({"BODY2":"body 2","BODY3":"body 3"});
or
	tpl.assign("BODY", "un titolo");


parsetpl(RETURN, FileHandle(s) )

The parse function is the main function in AspTemplate. It accepts a new key value pair where the key is the TARGET and the values are the SOURCE templates. There are three forms this can be in:

	tpl.parsetpl(MAIN, "main");		// regular
	tpl.parsetpl("MAIN", ["main", "body"]);	//compound
	tpl.parsetpl(MAIN, ".body");		// append

In the regular version, the template named "main" is loaded if it hasn't been already, all the variables are interpolated, and the result is then stored in AspTemplate as the value MAIN. If the variable "{MAIN}" shows up in a later template, it will be interpolated to be the value of the parsed "main" template. This allows you to easily nest templates, which brings us to the compound style.

The compound style is designed to make it easier to nest templates. Contrary to the PHP3 class, the following are not equivalent:

	tpl.parsetpl(MAIN, "main");
	tpl.parsetpl(MAIN, ".body");
	
	// is not the same as:
	
	tpl.parsetpl("MAIN", ["main", "body"]);

In the first (regular + append) example, the main template gets parsed into the variable MAIN, and the body template gets appended to same the variable MAIN. If the second (body) template contains a reference to MAIN (eg {MAIN}), the contents of the MAIN variable (eg the main template with its variable interpolated) get interpolated into the (body) template.

In the second example, the MAIN variable does not interpolate in the second template.

I do not know if a more consistent behaviour (such as the PHP3 class) would be desirable, I am open to comments.

The append style allows you to append the parsed results to the target variable. Placing a leading dot . before a defined file handle tells AspTemplate to append the parsed results of this template to the returned results. This is most useful when building tables that have an dynamic number of rows - such as data from a database query.


strict_on()

When strict_on() is on (it is on by default) all variables found during template parsing that are unresolved will be left in the output document. This was done for two reasons: to allow for parsing to be done in stages (i.e. multiple passes), and to make it easier to identify undefined variables since they appear in the parsed output. If you want to replace unknown variables with an empty string, see: no_strict().


strict_off()

Does not display unresolved template variables in the output document. A call to strict_off() is required to replace unknown variables with an empty string. By default, all instances of AspTemplate behave as is strict_on() was called. Also, strict_off() must be set for each instance of AspTemplate;


fastprint(HANDLE)

The method FastPrint() prints the contents of the named variable. If no variable is given, then it prints the last variable that was used in a call to parse() which I find is a reasonable default.

	tpl.fastprint("MAIN");	// continuing from the last example, would
									// print the value of MAIN


OTHER METHODS


No other methods are implemented in AspTemplate. If you decide to implement your own, please send me a copy of the code.


Variables

A variable is defined as:

    {([A-Z0-9_]+)}

This means, that a variable must begin with a curly brace '{'. The second and remaining characters must be uppercase letters or digits 'A-Z0-9'. Remaining characters can include an underscore. The variable is terminated by a closing curly brace '}'.

For example, the following are valid variables:

    {FOO}
    {F123F}
    {TOP_OF_PAGE}


Variable Interpolation (Template Parsing)

    Assume:

    $FOO = "foo";
    $BAR = "bar";
    $ONE = "1";
    $TWO = "2";    
    $UND = "_";
    
    Variable    Interpolated/Parsed
    ------------------------------------------------
    {FOO}            foo    
    {FOO}-{BAR}      foo-bar
    {ONE_TWO}        {ONE_TWO} // {ONE_TWO} is undefined!    
    {ONE}{UND}{TWO}  1_2
    ${FOO}           $foo
    $25,000          $25,000
    {foo}            {foo}     // Ignored, it's not valid, nor will it
                               // generate any error messages.


VERSION This is Revision 0.1 Nov 15, 1999 ludo@sumatrasolutions.com


AUTHOR

Original Perl module CGI::FastTemplate by Jason Moore jmoore@sober.com

PHP3 port by CDI cdi@thewebmasters.net

JScript port by ludo ludo@sumatrasolutions.com

JScript Version Copyright (c) 1999 Sumatra Solutions. All Rights Reserved

PHP3 Version Copyright (c) 1999 CDI, cdi@thewebmasters.net, All Rights Reserved.

Perl Version Copyright (c) 1998 Jason Moore jmoore@sober.com. All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the GNU General Artistic License, with the following stipulations;

Changes or modifications must retain these Copyright statements. Changes or modifications must be submitted to both AUTHORS.

This program is released under the General Artistic License.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Artistic License for more details. This software is distributed AS-IS.

Address Bug Reports or Comments on THIS JScript VERSION ONLY to

ludo@sumatrasolutions.com

The latest version of this class should be available from the following locations:

http://www.sumatrasolutions.com/asptemplate/


DOCUMENTATION

Sascha Schumann has written a very nice PHP3 FastTemplate tutorial. It's on the PHPBuilder.com web site at;

http://www.phpbuilder.com/

This is a modified version of the PHP3 FastTemplate man page, originally written by CDI

This is not a complete port, a lot of methods of the Perl and PHP3 versions were not implemented in this port since I had no need or use for them.

$Id: asptemplate.htm,v 1.2 1999/11/15 22:12:58 ludo Exp $


Article Information
Article Title: A JScript Port of the Perl/PHP FastTemplate Module
Article Author: Scott Mitchell
Published Date: Sunday, January 02, 2000
Article URL: http://www.4GuysFromRolla.com/webtech/010200-1.shtml


Copyright 2017 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers