The TEMPLATE keyword is used to include blocks of code from an external code template file that will ultimately be processed to a string. The syntax is as follows:

var sb = new StringBuilder()
TEMPLATE "FileName.sling.t", sb

The compiler will then read the file given as parameter (eg. "FileName.sling.t" above), and will process it as a text template, expanding its contents accordingly, turning the TEMPLATE statement to a series of statements that appends output to the variable given as the second parameter (above, variable sb). For example, consider the following template:

// This is a template. It can contain data or code or text of
// any format. It may also code embedded Sling code blocks:
{%
	foreach(value in values) {
		%} VALUE: value %{
	}
%}

When you now save this template eg. in a file named "template.sling.t", and include it in your Sling code as follows:

var values = [ "first", "second", "third" ]
var sb = new StringBuilder()
TEMPLATE "template.sling.t", sb

The compiler will then expand you TEMPLATE statement to perform the functionality that is equivalent to you having manually written the following code:

var values = [ "first", "second", "third" ]
var sb = new StringBuilder()
sb.append("// This is a template. It can contain data or code or text of\n")
sb.append("// any format. It may also code embedded Sling code blocks:\n")
foreach(value in values) {
	sb.append(" VALUE: value ")
}

The end result is that the embedded Sling code executes, and the output of the template processing is placed in the sb variable. Note how the template is able to directly access the variable values that is declared in the scope of the TEMPLATE statement.


Twitter Facebook LinkedIn Youtube Slideshare Github