Script Formats
Digest
Introduction to Script Formats
Script Formats are used to transform data from an XML document into an XML document that can be presented in some meaningful manner.
Script Formats use the Velocity Template Language syntax. Velocity is a templating engine created by the Apache Group. In contrast to XSL, which is declarative, Velocity is a procedural language and should be familiar to people with JavaScript, PHP, Perl and Python experience.
Concept
Uses for Script Formats
In Cascade, Script Formats are applied (along with a Block) to a specific region in a Page. Applying both the Block and the Format together ensures that the Format will style the Block’s XML content appropriately for that Page before the Block is substituted into a page region. Using Script Formats with blocks also makes Blocks reusable in the sense that one Block can be styled in many different ways to output the same content with different looks and feels.
Script Formats can also be assigned to the default region of a Page using a Structured Data Definition. In this case, the Script Format styles the user-supplied structured content in a way that is meaningful for that Page.
It is important to note that existing XSLT Formats cannot be converted into Script Formats directly. Pasting Velocity Templating Language (VTL) code into an existing XSLT Format will result in an XML validation error upon submission. A new Script Format must be created in order to utilize VTL.
Assigning Script Formats
Script Formats can be assigned to individual regions at the Page, Configuration Set, or Template level. Unlike their XSLT Format counterparts, Script formats cannot be applied to entire pages at the Page, Configuration Set, or Template level.
A Script Format assigned to a region will transform the content of the Block assigned to that region. In the case of the Default region, it's possible to assign an Script Format without a Block. In this case, the page's Structured Data XML or the raw WYSIWYG HTML will be used as the content to which the Format is applied.
A Script Format assigned to a Page will transform the complete assembled content of that Page after all the region level Formats have been applied.
Inheritance of Script Format Assignments

- Page Configuration Sets inherit and can optionally override the XSLT Format assignments of the Templates associated with its Page Configurations.
- Pages inherit and can optionally override the XSLT Format assignments of its associated Page Configuration Set
Technical
Velocity Resources
With the release of Cascade Server 6.10, the Velocity engine has been updated to version 1.7 from version 1.5 previously. The complete Velocity Users' Guide is available on Apache's website (for those running pre-6.10 versions of Cascade, the user guide for version 1.5 of the velocity engine is available here). Users should read this guide first as it provides definitions for terms that follow (e.g. the Velocity "context"). In addition to knowledge of Velocity, users of Script Formats will also need to be familiar with the JDOM API. JDOM is a Java-based framework for "accessing, manipulating, and outputting" XML data based on the original W3C Document Object Model.
Creating Script Formats
Format are used to format reusable content blocks.
To create a new Format:
- In the Home area, select New -> Default -> Format.

- Choose the Script radio button.
- On the Content pane:
Enter your Script Content.
In versions 6.4 and newer, the text editor displayed supports syntax highlighting for the Velocity Templating Language (VTL) and Velocity comments, variables, and derivatives as well as HTML tags. The syntax-highlighting text editor can be turned on/off using the "Advanced Editor" button at the bottom of the editor.
- On the Metadata pane:
Enter any Metadata desired. - On the System pane:
Name - Type in the name of your new format. Since most formats are specific to a particular block, it's often best to give them matching names.
Parent Folder - This is where the format will be stored. It's most useful to store formats in a central or common location. - Click Submit to save your format.
Script Formats may be edited or deleted by selecting the format and choosing the appropriate tab.
Velocity Context
The Velocity context contains objects that can be accessed when writing a Script Format. As of Cascade 5.7, the only object supplied is a representation of the exact same XML that would be passed to an XSLT Format assigned to the same region. The XML is represented in a document object model using JDOM. The data in the object is accessed through the functions of the JDOM API. The context object and entry point into the available data is called the "contentRoot" and it is a JDOM Element.
In the case where the block assigned to the region or the content being supplied from the page's default region or structured data is not wrapped by a root element the root element is "system-xml".
A handful of tools were made available in the Velocity context in Cascade 6.2, and as of Cascade 6.10, still more tools have been added to the Velocity context. See "Velocity Tools" below for more information.
The context currently contains the following objects:
As of 6.2:
- contentRoot - JDOM Element containing the XML supplied for the current region. This content could be coming from a block or the page's own structured data or xml. To view the raw XML, simply apply no Format to that region.
- _DateTool - Tool used to manipulate numeric date values.
- _XPathTool - Tool used to access data in an XML data structure using the XPath language.
- _SerializerTool - Tool used to serialize an XML data structure to text.
- _SortTool - Tool used to sort collections of JDOM Elements
- _StringTool - Tool containing useful string manipulation methods
- _DisplayTool - Tool containing some convenient diplay/formatting utilities for various data types.
- _EscapeTool - Tool used to safely escape text for a variety of different languages, including XML, HTML, JavaScript, etc.
- _MathTool - Tool containing numerous useful math and number conversion/manipulation methods.
- _NumberTool - Tool containing convenient number formatting methods.
As of 7.0:
- _FieldTool - Tool providing access to Java constants, such as Calendar.DAY_OF_WEEK, etc.
In addition, 6.10 includes an upgrade of the Velocity Engine to version 1.7, which includes a number of improvements to the native language features. For more on the improvements to Velocity in Cascade 6.10, check out the 6.10 Script Formats Webinar.
Note: The original release of 6.10 also included a LoopTool in the Velocity Context. Because this tool has compatability issues with version 1.7 of the Velocity Engine, and because the 1.7 engine includes native language support for virtually all of the LoopTool functionality, this tool will be removed as of 6.10.2, and we encourage using the native looping enhancements outlined below in lieu of the LoopTool.
Objects in the context are referenced using a dollar sign ($) before the name of the object.
Velocity Example
Here is a short code example of an XSL that outputs an unordered list of links to all the pages and folders under the root element of an index block.
Here is a code that will produce the same result using Velocity and JDOM.
Notice that the Velocity equivalent in this case is considerably more succinct and the syntax closely resembles other procedural, web-programming languages like PHP, ASP.NET, etc.
Velocity Engine 1.7 improvements:
With the release of Cascade 6.10, there are enhancements to Velocity's native support for loop management. These improvements make it easier to track iteration counts, indexes and nested loops. Specifically, the #break directive is now supported within Velocity scripts in Cascade and within every #foreach loop, there is now a new native reference, $foreach. The $foreach reference gives access to information about the current loop, like the current index and count through properties: $foreach.index, $foreach.count, $foreach.hasNext, etc.
The following example shows how you can easily reference the current index of an iteration and use this index to reference a corresponding index of a parallel list:
Line-by-line explanation:
1. Creates an array, $keys, containing the values "first", "second", "third" and "fourth".
2. Creates an array, $values, containing the values "value 1", "value 2", "value 3" and "value 4".
3. Begins a looping structure which will loop over each item in the $keys array.
4. Outputs each item in the $keys array, alongside the corresponding item from the parallel $values array, using the native $foreach.index property to reference the identical index as the current iteration of the $keys list..
5. Ends loop.
Additionally, for nested loops, the $foreach reference contains pointers to parent loop structures through $foreach.parent. The $foreach.parent reference contains all the same properties as $foreach: count, index, hasNext, etc. You can reference nested loops multiple levels deep using references like $foreach.parent.parent.parent, etc. Below is an example of how properties of a parent loop can be referenced from within a child loop:
Line-by-line explanation:
1. Creates an array, $outerList, containing values "outer 1", "outer 2", "outer 3" and "outer 4".
2. Creates an array, $innerList, containing values "inner 1", "inner 2", "inner 3", "inner 4" and "inner 5".
3. Begins a loop over $outerList.
4. Outputs each value in $outerList.
5. Begins a nested loop over $innerList.
6. Tests the current iteration count of the outer loop, using native $foreach.parent.count.
7. If the iteration count conditions from line 6 are met, stop iteration $innerList only.
8. Ends #if statement.
9. Outputs each value in $innerList, indented 3 spaces.
10. Ends the inner #foreach loop.
11. Ends the outer #foreach loop.
Velocity Tools
Velocity Tools are a collection of common functions that simplify the content manipulation process when using Velocity. Below are explanations of each tool and code samples.
Comparison Date Tool
The Comparison Date Tool allows users to format numeric date values and compare them with other date values in a Velocity template. For example, let's say you have an Index Block that indexes a Folder and includes system metadata. Dates in Index Blocks are output in the Java timestamp format, which is Unix time format with 3 additional digits for milliseconds. With this tool, users can easily convert these Unix times to virtually any format they like with a very small amount of Velocity code.
The following example demonstrates how to perform a number of different operations using the Comparison Date Tool. Below the example are explanations for each line. Note that a Date is actually a Java Date. See information regarding Java Dates for more details.
Note: The block used with this example must contain at least one 'system-page' element and must include system metadata.
Line-by-line explanation:
- Creates a new variable, $originalDate, which is a Date representing today's date.
- Begins iterating over the system-page children of the contentRoot.
- Creates a new variable, $pubDate, which is the Date representation of the current system-page's last published date.
- Outputs the current system-page's last published Date in a "medium" format. See definitions for friendly date formats like "medium".
- Outputs the current system-page's last published Date in a custom format specified using pre-defined formatting characters. For specifics regarding these formatting characters, see date and time patterns.
- Computes the time difference between two Dates. This example uses today's Date and the current system-page's last published Date. By default, the difference() method will return a value that is the largest unit difference between the two Dates. For example, if today's date were May 25, 2009 and the system-page's last published date were May 18, 2007; then the value returned from the difference() method would be 2 for 2 years difference. For more information regarding the difference() method and all other available date comparison methods see ComparisonDateTool.
The Date Tool's getDate(String) method is not actually a part of the standard Date Tool supplied by Velocity. It's purpose is very simple though. It takes a string and converts it into a Java Date which makes it very easy to manipulate using other methods contained in the Date Tool. Check out information regarding the Date Tool.
XPath Tool
Support for XPath statements is now available as part of Cascade's Velocity resources. This allows users to query the JDOM XML structure using an XPath expression, similar to how this would be performed if you were using an XPath expression in the "select" attribute of an XSL template. For example, if you want to retrieve all system-page elements within an index block; you can now do so with an XPath query, rather than by manually drilling down in the JDOM structure.
Below is an example of how you can query for all the groups the current user is member of and output them as an unordered list.
Note: The Index Block used with this example must include user information.
Line-by-line explanation:
- Retrieves the full-name node from the index block by using the XPath Tool and stores it in the variable $fullname.
- Retrieves the list of group nodes from the index block by using the XPath Tool and stores it in the variable $groups.
- Outputs a welcome message including the current user's name.
- Opens an unordered list.
- Begins iterating over the group nodes.
- Outputs each group name as a list item.
- Terminates the iteration.
- Closes the unordered list.
Serializer Tool
The Serializer Tool allows users to take any node in the XML hierarchy backed by JDOM and serialize it into its underlying XML. This makes it possible to do things like retrieve the contents of a WYSIWYG node in a structured data Page and convert it straight to XML without having to output each node in the JDOM tree manually.
The Serializer Tool's serialize() method takes two arguments. The first argument can be any JDOM Element. The second is a boolean which determines whether or not the XML for the Element passed as the first argument is removed from the output or not.
Note: The block used with this example must include page XML inline; the page used must employ a structured Data Definition. If these criteria are not met, the output of this example will not be relevant.
Line-by-line explanation:
- Retrieves the structured data portion of the system-page node corresponding to the current Page by using the XPath Tool and stores it in the variable $sd.
- Serializes the JDOM object representing the root structured data element into raw XML. Notice that the second argument to the serialize() method is false meaning the root element of the XML chosen to be serialized will NOT be removed from the output.
Sort Tool
The Sort Tool is modeled after the <xsl:sort/> directive and contains two methods: sort() and addSortCriterion(). The sort() method takes a list of JDOM Elements, which can be acquired using the XPath Tool, and sorts them based on the criteria specified using the addSortCriterion() method. The addSortCriterion() method takes 5 arguments: a selection string, language, data type, sort order, and case order. Below is a description of each argument.
Method addSortCriterion():
- selection string - An XPath expression specifying the node/node-set on which to sort.
- language - Specifies the two-letter ISO-639 language code to be used when sorting text data, defauls to "en".
- data type - Either "text", "number", or "qname", defaults to "text".
- sort order - Either "ascending" or "descending", defaults to "ascending".
- case order - Either "lower-first" or "upper-first", specifies whether upper-case or lower-case letters come first when sorting, defaults to "lower-first".
Note: The block used with this example must contain at least one 'system-page' element; otherwise the output will contain no results.
Line-by-line explanation:
- Uses the XPath Tool to retrieve all system-page nodes in the contentRoot.
- Adds a new sort criterion that specifies that items should be sorted by the value of the name element with the language defaulting to english, the data type being text, sort order ascending, and with upper case letters being placed first in order when comparing two pages with the same name.
- The Sort Tool is being used to sort the system-pages. Notice that you do not have to issue a #set directive. This is because the sorting is done "in place" and does not require that a new list be created.
- (blank)
- Outputs a heading for our list of pages.
- Begins iterating over our sorted list of system-pages.
- Outputs each system-page's name.
- Ends iteration.
String Tool
The String Tool contains two methods, substringBefore() and substringAfter(), which may be familiar to users who have used XPath string functions at some point. Both methods take two string arguments. The first argument is searched to determine if it contains the second argument. If the second argument is found in the first, then a portion of the first argument is returned. Depending on which method is used, either the portion of the first argument that comes before the second argument is returned (substringBefore()) or the portion of the first argument that comes after the second argument is returned (substringAfter()). If the second argument cannot be found in the first, then an empty string is returned.
For example, if one were to call the substringAfter() method with the arguments "/path/to/asset" and "path", the result would be "/to/asset" because "/to/asset" is the prtion of "/path/to/asset" that comes after "path". Likewise, if you were to call substringBefore() with the arguments "/path/to/asset" and "asset", the result would be "/path/to/".
Note: The block used with this example must contain at least one 'system-page' element; otherwise the output will contain no results.
Line-by-line explanation:
1-6. Same as Sort Tool explanation.
7. Page name and path are output but only the part of each page's path that follows the string "test" is returned. This could be used if pages in the index are contained in the "/test" folder and it was not desired for that section of the path to be included in the output.
8. Same as Sort Tool explanation.
6.10 Tools:
For additional coding samples for the new 6.10 tools and native language improvements, see our GitHub repository.
Display Tool
The Display Tool contains numerous convenience methods for formatting various types of data for display. A few examples are provided below, and the full API documentation may be found here.
Displaying Lists: The Display Tool list() method displays each item in the specified list of items, separated by the specified delimiter.
Line-by-line explanation:
1. Creates an array of numbers 1 through 5.
2. Outputs a heading for our diplayed list of numbers
3. Outputs each number in the array, separated by a comma -- i.e. "1,2,3,4,5"
Displaying text which may be singular or plural at run-time: The Display Tool plural() method will automatically return the plural form of the specified singular word, if necessary, based on the specified integer value. You may also explicitly specify the plural form of the word for words which do not follow standard pluralization rules.
Line-by-line explanation:
1. Creates an array containing 4 "apples"
2. Creates an array containing 1 "apple"
3. (blank)
4-5. Outputs: "There are 4 apples in List 1"
6-7. Outputs: "There is 1 apple in List 2"
Stripping HTML tags: The Display Tool stripTags() method allows you to strip HTML tags from text.
Line-by-line explanation:
1. Creates text variable containing HTML tags
2. Outputs "Text output directly: This is some text with HTML tags."
3. Outputs "Text with HTML tags stripped: This is some text with HTML tags."
Truncating long text: The Display Tool truncate() method allows you to truncate long text after a specified number of characters. You may also specify that the truncation occur only after a complete word -- i.e. not in the middle of a word.
Line-by-line explanation:
1. Creates a variable, $longText, containing: "That is some really, really, really, long text you've got there."
2. Outputs the full text of $longText
3. Outputs: "Truncated text: That is some really, really, r..."
4. Outputs: "Truncated at word: That is some really, really,..."
Graceful display of null values: The Display Tool alt() method checks the value of the given object and returns the specified alt text if the object is null, otherwise the original value is returned.
Note: The index block used for the above example must have the "Append Calling Page Data" option selected, otherwise $title will always be null.
Line-by-line explanation:
1. Sets a variable, $title, containing the contents of the current page's Title metadata field (if provided).
2. Outputs the title of the current page, if one was provided, otherwise outputs "No Title Provided."
Escape Tool
The Escape Tool contains programming language-specific escape functionality, as well as methods and properties for outputting safely escaped special characters within your Velocity scripts. Some examples are shown below and the full API documentation may be found here.
Escaping for XML: The Escape Tool xml() method safely escapes any special characters specifically for XML output. It is important to note than in almost all cases, the xml() method will be preferable to the html() method when escaping content within Cascade, due to Cascade's more strict XHTML validation of content. This is true even when escaping content for HTML output within Cascade.
Note: The index block used for this example must have the "Append Calling Page Data" option selected, and the page on which this format executes should have data set for the "Summary" metadata field as described below.
Line-by-line explanation:
1. Sets a text variable, $xml, containing the value of the current page's "Summary" metadata field. For this example, edit the page to set the value of the Summary field to: "bread" & "butter" (with quotation marks included).
2. (Commented out) If un-commented, this line would attempt to output the contents of $xml un-escaped and would result in a run-time error because the un-escaped special characters are not valid XML.
3. Outputs: "bread" & "butter" with the quotation marks and ampersand characters safely escaped for XML output.
Escaping for JavaScript: The Escape Tool javascript() method safely escapes any special characters specifically for output within JavaScript code.
Note: The index block used for this example must have the "Append Calling Page Data" option selected, and the page on which this format executes should have data set for the "Teaser" metadata field as described below.
Line-by-line explanation:
1. Sets a variable, $javascript, containing the value of the current page's "Teaser" metadata field. For this example, edit the page to set the value of the Teaser field to: I didn't say "Stop!"
2. Opening script tag.
3. (Commented out) If un-commented, this line will attempt to display the un-escaped value of $javascript in a pop-up alert, but will instead generate a JavaScript error and fail due to the un-escaped special characters.
4. Outputs a JavaScript pop-up alert containing the text: I didn't say "Stop!" with all special characters safely escaped for JavaScript.
5. Closing script tag
Pre-defined special characters: The Escape Tool also provides several pre-defined, safely-escaped (for Velocity) special characters.
Line-by-line explanation:
1. Outputs a safely-escaped dollar sign ($).
2. Outputs a safely-escaped hash (pound key) (#).
3. Outputs a safely-escaped single-quote (').
4. Outputs a safely-escaped double-quote (").
5. Outputs a safely-escaped backslash (\).
6. Outputs a safely-escaped exclamation mark (!).
Math Tool
The Math Tool provides convenience methods for converting numeric text to real numbers are performing various mathmatical operations. Some examples are provided below and the full API documentation can be found here.
Converting numeric text to real numbers: The Math Tool provides simple methods for converting numeric text -- such as the values returned from XML nodes -- into real numbers, suitable for performing math operations. For example, previously, to convert the numeric text derived from a page metadata field to a real number in Velocity would require the following:
Note: This example assumes an index block, with "Append Calling Page Data" selected and a page with the "Teaser" metadata field set to some numeric text, i.e. "25".
Line-by-line explanation:
1. Initialize a placeholder $numText variable to a string containing valid numeric text. This step is necessary to avoid a runtime error when calling parseInt() later, as parseInt() is not written to fail gracefully for a Velocity script -- i.e. it throws an exception rather than simply returnin null on failure.
2. Assign a new value to $numText, derived from the contents of the current page's "Teaser" field.
3. Create a dummy integer variable, $realNumber, and set its value to a real number.
4. Use the dummy integer variable, $realNumber, to convert $numText to an integer value.
The above is obviously neither the most efficient nor intuitive way of converting numeric text to a real number. With the Math Tool, the above can be accomplished with the following code:
Line-by-line explanation:
1. Create a variable, $numText, and assign it a value derived from teh contents of the current page's "Teaser" field.
2. Create a variable, $realInt, using $_MathTool.toInteger() to convert the $numText into a real integer value (i.e. 25).
3. Create a variable, $realDouble, using $_MathTool.toDouble() to convert $numText into a real double (floating-point decimal) value (i.e. 25.39).
Performing math operations: The Math Tool also has numerous methods for performing various math operations.
Line-by-line explanation:
1. Creates an array of numeric values, called $numbers.
2. Calculates the average of all items in the $numbers array, and stores the result in a variable, $average.
3. Calculates the total of all items in the $numbers array, and stores the result in a variable, $total.
4. Outputs the total (268.3).
5. Outputs the average (44.71666666666667).
6. Outputs the ceiling of $total (total = 268.3, so ceiling = 269).
7. Outputs the floor of $total (total = 268.3, so floor = 268).
8. Outputs the average, rounded to the nearest whole number (45).
9. Outputs the average, rounded to 2 decimal places (44.72).
Number Tool
The Number Tool contains several method for formatting various types of numeric data. Some examples are shown below and the full API documentation may be found here.
Line-by-line explanation:
1. Creates a variable, $myNumber, and assigns it a numeric value (13.55).
2. Outputs $myNumber as a percentage (1,355%).
3. Outputs $myNumber as currency ($13.55)
4. Outputs $myNumber as an integer (13).
7.0 Tools:
Field Tool
The Field Tool provides access to Java public constant values, which are otherwise inaccessible in Velocity scripts. Some examples are shown below and the full API documentation for the tool may be found here.
Static variables are not natively accessible in Velocity – nor are there any plans to make them accessible natively in the future. As a result, constants such as Calendar.DAY_OF_WEEK, Calendar.MONTH, Calendar.YEAR, etc., are inaccessible in Velocity scripts. Among other things, this makes certain date manipulation functions in Velocity quite unintuitive. For example, adding/subtracting time:
Line-by-line explanation:
1. Get a java.util.Calendar object using $_DateTool.
2. Get a java.util.Date object representing the current system date/time.
3. Output the value of the current system date/time.
4. Set the calendar's date/time to the current system date/time.
5. Add 1 day to the calendar's date/time (6 is the value of the constant field Calendar.DAY_OF_YEAR, while 1 is the number of days we are incrementing the calendar's date/time value).
6. Output the current system date/time, plus 1 day (i.e. tomorrow).
Note that without Field Tool, one must simply know that the literal value of Calendar.DAY_OF_YEAR is 6. Likewise, for any other portion of the date to be manipulated, the literal value of the appropriate constant must be known. However, with Field Tool, the above could be accomplished without hard-coding the field value for Calendar.DAY_OF_YEAR like so:
Line-by-line explanation:
1. Get a java.util.Calendar object using $_DateTool.
2. Get a java.util.Date object representing the current system date/time.
3. Output the value of the current system date/time.
4. Set the calendar's date/time to the current system date/time.
5. Add 1 day to the calendar's date/time, using $_FieldTool to access the value of the constant field Calendar.DAY_OF_YEAR.
6. Output the current system date/time, plus 1 day (i.e. tomorrow).
Constant values may be accessed by passing in one of three values to the $_FieldTool.in() method:
1. An object reference to an instance of the class containing the desired constant value:
2. The fully-qualified Java class name (including package) of the class containing the desired constant value:
3. A literal value of the class type containing the desired constant value:
Finally, in addition to core Java constants, the following Cascade-specific constant values have been made accessible via $_FieldTool, like so:
Line-by-line explanation:
1. The Cascade applicaton version
2. The TinyMCE version
3. The Cascade DB update version
4. The Cascade copyright year

