Template (class)

Categories:Text

Overview

Summary

The Template class is used to build text output in an object-oriented manner, by combining the contents of template file with a hash of values. Named properties of the hash map directly to named {placeholder} variables within the template, which is populated to produce new output.

By separating content (template) and data (object properties) it makes for cleaner and more easily-maintainable code, rather than lots of multiline strings, escaping, and concatenation.

Also see the SimpleTemplate class for a more lightweight approach to templating.

Contents

Concept

Template file

The Template class is always used in conjunction with physical text files that are stored on disk and loaded via a URI (this is in contrast to the SimpleTemplate class which allows you to simply pass in a template string.

A typical template file might look something like the following:

package {packagePath}
{
    {>imports?}
	
	class {className}
    {
        function {className}({params?})
        {

        }
		
		{>methods?}
    }
}

This would populate the above template file with a packagePath, className and methods data, but would leave the optional imports and params placeholders to be deleted automatically.

Placeholder variables

There are three types of placeholder that can be used in templates, indicated by the following syntax:

  • {placeholder} - a normal placeholder that will be populated by the same-named value of the data object
  • {>indented} - an indented placeholder, which will retain its indentation over multiple lines
  • {optional?} - an optional placeholder, which will be removed after rendering if not replaced
  • {default=Value} - a default value placeholder, the value of which will be inserted into the document if not replaced

The indented and optional types can also be combined if necessary.

Data object

The data object can be any object or value with properties that can be mapped to the named placeholder variables used in the template. This includes object literals, custom classes, or standard classes such as LibraryItems.

Note that the values of objects can also be other Templates themselves. This allows you to nest Templates inside each other, which is extremely useful when you want to break up a single template file into multiple, discrete parts:

var data =
{
    packagePath: 'some.project',
    className: 'SomeClass',
    methods: [new Template('method.txt', method1), new Template('method.txt', method2)]
}

var template = new Template('class.txt', data);

API

Template(uri, data)

Handes loading and population of text data, including nested templating and indentation

Parameters:

  • uri String A URI or path to the template file
  • data Object An object of key:value pairs

The following example combines a basic object literal with a template, and renders it:

var template = new Template('email.txt', {name:'Dave', greeting:'how are you doing?'});
trace(template.render());
Hello there Dave, how are you doing?

load(uri)

Loads the template source text file

Parameters:

  • uri String A URI or path to the template file

Returns:

  •   Template Itself

You may have need to change the template after it has been set; for example rendering the same data to different outputs.

The following example loads in a new template then renders the output:

var template = new Template(uri, data);
template
    .load(newURI)
    .render();

save(uri, overwrite)

Render and save the template to a file

Parameters:

  • uri String The uri of where to save the file
  • overwrite Boolean An optional Boolean specifying whether to overwrite an existing file or not, defaults to false

Returns:

  •   Template Itself

The following example saves the output of a class template to the project's src directory:

template.save(projectURI + 'src/' + package + '.as', true);

set(data, value, append)

Set the values for the placeholders in template

Parameters:

  • data Object An object of key:value pairs
  • data String A key name
  • value mixed Any value that can be converted to a string, even another Template instance
  • append Boolean Append teh value, rather than replacing it

Returns:

  •   Template Itself

The following example sets the data of a template in three different ways:

var template = new Template(uri);
template    
    .set(data) // a data object    
    .set('text', 'One two three'); // a named property and value
    .set('text', ' four five six', true); //concatenate data to the previous value

indent(indent)

Set a global indent for the final rendered output

Parameters:

  • indent Number The number of tabs to indent
  • indent String A string that will be used as the indent

Returns:

  •   Template Itself

By default, the data in a template is not indented, but you may wish to indent multiline blocks of data.

The following example indents the data by 2 tabs:

template.indent(2);

render()

Renders the Template and all its placeholder values

Returns:

  •   String The rendered template

The following example returns the contents of the template as a String:

var results = template.render();

clone()

Return a copy of the object

Returns:

  •   Template An independant copy of the object

The following example creates a copy of the template:

var copy = template.clone();

toString()

Returns the String representation of the Template

The following example prints a summary of the Template instance to the Output panel:

trace(template);
[object Template file="user/config/templates/actionscript.as"]

2 Responses to Template (class)

  1. Hugh Campbell says:

    var template = Template(‘email.txt’, {name:’Dave’, greeting:’how are you doing?’});
    trace(template.render());

    think that’s “new Template()” ?

    though for a mo it was some sort of factory method…

  2. Dave Stewart says:

    Good spot, thanks :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>