Skip to main content

Velocity Tools

Cascade CMS's Velocity Tools are a collection of functions that can be used to retrieve and manipulate content in conjunction with Apache Velocity Template Language.

Global Variables

These variables are available in every Velocity Format without any additional setup.

Global variables available in Velocity Formats.
Variable Output Type Description
$contentRoot Element Returns a JDOM Element containing the XML supplied for the current region.
$currentPage PageAPIAdapter Returns the current page as an API object.
$currentPagePath String Returns the path of the current page.
$currentPageSiteName String Returns the name of the current page's site.
$enabledCustomDirectives ArrayList Returns all available custom directives in the CMS environment.

Locator Tool

The Locator Tool retrieves assets at a given path as API objects. Optionally, a site name can be specified to locate assets in a different site. Added in 7.4

Locator Tool methods.
Method Parameters Description
$_.locate(path, type) path (String), type (String) Locates an asset at the given path with the specified type. Valid types: block, file, folder, format, page, reference, symlink.
$_.locate(path, type, site) path (String), type (String), site (String) Locates an asset at the given path with the specified type in the specified site.
$_.locateBlock(path) path (String) Locates a Block at the given path.
$_.locateFile(path) path (String) Locates a File at the given path.
$_.locateFolder(path) path (String) Locates a Folder at the given path.
$_.locateFormat(path) path (String) Locates a Format at the given path.
$_.locateLinkable(path) path (String) Locates a Page, File, or External Link at the given path.
$_.locatePage(path) path (String) Locates a Page at the given path.
$_.locateReference(path) path (String) Locates a Reference at the given path.
$_.locateSymlink(path) path (String) Locates an External Link at the given path.

Each method also accepts an optional second parameter for site name (e.g. $_.locatePage(path, site)) to locate assets in a different site.

Velocity
## Locate a page in the current site
#set ($aboutPage = $_.locatePage("/about"))

## Locate a file in a different site
#set ($logo = $_.locateFile("/images/logo.png", "Global"))

## Locate using the generic method
#set ($myBlock = $_.locate("/blocks/header", "block"))

Query API

The Query API allows you to construct queries using chained methods to filter and retrieve assets from the CMS. Start by creating a query object, choose a query type, set optional filters and sorting, then execute.

Query construction

Primary query methods.
Method Parameters Description
$_.query().byContentType(name) name (String) Query assets by Content Type name.
$_.query().byMetadataSet(name) name (String) Query assets by Metadata Set name.
$_.query().byDataDefinition(name) name (String) Query assets by Data Definition name.

Filters

Query filter methods for narrowing results.
Method Parameters Description
.bySiteName(name) name (String) Restrict results to a specific site.
.byFolderPath(path) path (String) Restrict results to assets within a single folder path. Accepts one path only.
.hasAnyPaths(paths) paths (String...) Fetch a known set of assets by their exact full paths (e.g., site://faculty/dept/sci/nye-william.php). Each value must be a complete asset path, not a folder. This is not a subtree filter.
.hasMetadata(field, value) field (String), value (String) Filter by a metadata field matching a specific value.
.hasAnyMetadataValues(field, values) field (String), values (String...) Filter by a metadata field matching any of the specified values.
.hasStructuredData(path, value) path (String), value (String) Filter by a structured data field matching a specific value.
.hasAnyStructuredDataValues(path, values) path (String), values (String...) Filter by a structured data field matching any of the specified values.
.hasStructuredDataByFieldId(id, value) id (String), value (String) Filter by a structured data field ID matching a specific value.
.hasAnyStructuredDataValuesByFieldId(id, values) id (String), values (String...) Filter by a structured data field ID matching any of the specified values.
.hasTag(tag) tag (String) Filter results to assets with the specified tag.
.hasAnyTags(tags) tags (String...) Filter results to assets with any of the specified tags.

Querying assets across multiple folders

.hasAnyPaths() is for fetching assets at specific, known paths — not for querying all assets within a folder or set of folders. To query assets across multiple folders, use one of these approaches:

  • Separate queries merged with #queryexecute: Run a byFolderPath() query for each folder and accumulate results into a shared list.
  • #queryfilter directive (supported in current versions of Cascade): Apply custom Velocity logic per asset before results are returned, allowing you to check multiple parent folder conditions in one query. See Query Tool Directives.

Asset type filters

Methods to include or restrict by asset type.
Method Description
.includeBlocks() Include Block assets in results.
.blocksOnly() Return only Block assets.
.includeFiles() Include File assets in results.
.filesOnly() Return only File assets.
.includeFolders() Include Folder assets in results.
.foldersOnly() Return only Folder assets.
.includePages() Include Page assets in results.
.pagesOnly() Return only Page assets.
.includeSymlinks() Include External Link assets in results.
.symlinksOnly() Return only External Link assets.

Additional options

Additional query options.
Method Description
.indexableOnly() Include only indexable assets in results.
.publishableOnly() Include only publishable assets in results.
.preloadDynamicMetadata() Preload dynamic metadata fields to avoid individual database trips per asset.
.preloadStructuredData() Preload structured data to avoid individual database trips per asset.
.searchAcrossAllSites() Expand the query to search all sites, not just the current one.

Sorting and limiting

Query sorting and result limiting.
Method Parameters Description
.sortBy(field) field (String) Sort results by the specified field. Valid values: author, created, description, displayName, endDate, keywords, modified, name, path, reviewDate, startDate, summary, title, teaser.
.sortDirection(dir) dir (String) Set sort order. Valid values: asc, desc.
.maxResults(n) n (int) Limit the number of results. Default is 100, maximum is 2,000 for .execute() and 100,000 for #queryexecute.

Example

Velocity
## Query all pages with the "news" content type, sorted by start date descending
#set ($newsItems = $_.query().byContentType("news").pagesOnly().sortBy("startDate").sortDirection("desc").maxResults(10).execute())
#foreach ($item in $newsItems)
  <h3>$item.metadata.title</h3>
  <p>$item.metadata.summary</p>
#end

Custom directives

The Query API supports three custom directives for advanced processing. See Query Tool Directives for detailed usage.

Custom query directives.
Directive Description
#queryfilter Execute logic on each asset before maxResults is applied, allowing custom filtering.
#querysortvalue Determine the sort value for each asset using custom logic.
#queryexecute Execute on each asset with support for up to 100,000 results. Assets are loaded one at a time to conserve memory.

Date Tool

The Date Tool handles date retrieval, formatting, and comparison. See Date Tool Essentials for in-depth usage patterns. Added in 6.2

Date Tool methods.
Method Parameters Return Type Description
$_DateTool.difference(date1, date2) date1 (Date), date2 (Date) ComparisonDateTool Returns the difference between two dates.
$_DateTool.format(format, date) format (String), date (Date) String Formats a date using the specified format string.
$_DateTool.getCalendar() — Calendar Returns the current date and time as a Calendar object.
$_DateTool.getDate() — or timestamp (long) Date Returns a Date object. Without arguments returns the current date; with a Unix timestamp in milliseconds, converts it to a Date.
$_DateTool.getDay() — Integer Returns the day of the month from the current date.
$_DateTool.getMonth() — Integer Returns the month from the current date (0 = January in Java).
$_DateTool.getTime() — long Returns the current time as a number (Unix timestamp in milliseconds).
$_DateTool.getValue(field, date) field (String), date (Date) Integer Returns the specified Calendar field value from a date.
$_DateTool.getYear() — Integer Returns the year from the current date.
$_DateTool.toDate(format, string) format (String), string (String) Date Converts a formatted date string to a Date object using the specified format pattern.
$_DateTool.toDays(timestamp) timestamp (long) long Converts a timestamp to days since epoch.
$_DateTool.toHours(timestamp) timestamp (long) long Converts a timestamp to hours since epoch.
$_DateTool.toMinutes(timestamp) timestamp (long) long Converts a timestamp to minutes since epoch.
$_DateTool.toMonths(timestamp) timestamp (long) long Converts a timestamp to months since epoch.
$_DateTool.toSeconds(timestamp) timestamp (long) long Converts a timestamp to seconds since epoch.
$_DateTool.toWeeks(timestamp) timestamp (long) long Converts a timestamp to weeks since epoch.
$_DateTool.toYears(timestamp) timestamp (long) long Converts a timestamp to years since epoch.
$_DateTool.whenIs(date) date (Date) String Returns a human-readable description of the time difference (e.g. "3 days ago").

Display Tool

The Display Tool provides methods to control the display of references and format strings. Added in 6.10

Display Tool methods.
Method Parameters Description
$_DisplayTool.alt(value, alternate) value (Object), alternate (Object) Returns the value if not null, otherwise returns the alternate.
$_DisplayTool.br(text) text (String) Prepends newlines with <br/> tags.
$_DisplayTool.capitalize(text) text (String) Capitalizes the first letter of the string.
$_DisplayTool.cell(text, length) text (String), length (int) Truncates or pads the string to the given length.
$_DisplayTool.list(list, separator) list (Collection), separator (String) Joins the list items with the specified separator.
$_DisplayTool.message(format, args) format (String), args (Object...) Formats a message string with the specified values.
$_DisplayTool.plural(count, singular, plural) count (int), singular (String), plural (String) Returns the singular or plural form based on count.
$_DisplayTool.space(count) count (int) Generates the specified number of spaces.
$_DisplayTool.stripTags(html) html (String) Removes HTML tags from the string.
$_DisplayTool.truncate(text, length) text (String), length (int) Truncates the string to the specified length. Supports an optional suffix and word-boundary truncation.
$_DisplayTool.uncapitalize(text) text (String) Uncapitalizes the first letter of the string.

Escape Tool

The Escape Tool provides methods for escaping content for various output contexts and accessing special characters. Added in 6.10

Special characters

Escape Tool special character methods.
Method Alias Character
$_EscapeTool.getB() getBackslash() \
$_EscapeTool.getD() getDollar() $
$_EscapeTool.getE() getExclamation() !
$_EscapeTool.getH() getHash() #
$_EscapeTool.getN() getNewLine() \n
$_EscapeTool.getQ() getQuote() "
$_EscapeTool.getS() getSingleQuote() '

Escape methods

Escape and unescape methods.
Method Parameters Description
$_EscapeTool.html(text) text (String) Escapes characters for safe use in HTML content.
$_EscapeTool.javascript(text) text (String) Escapes characters for safe use in JavaScript strings.
$_EscapeTool.xml(text) text (String) Escapes characters for safe use in XML content.
$_EscapeTool.url(text) text (String) Encodes a string for use in a URL.
$_EscapeTool.unicode(hex) hex (String) Converts a hex code to its Unicode character equivalent.
$_EscapeTool.unescapeHtml(text) text (String) Unescapes HTML entities back to their original characters.
$_EscapeTool.unescapeJavaScript(text) text (String) Unescapes JavaScript escape sequences.
$_EscapeTool.unescapeXml(text) text (String) Unescapes XML entities back to their original characters.

Field Tool

The Field Tool provides access to Java public constant values via reflection. Added in 7.0

Field Tool methods.
Method Parameters Description
$_FieldTool.in(className) className (String or Class) Returns an object providing access to the class's public static variables.
Velocity
## Access the Integer.MAX_VALUE constant
#set ($maxInt = $_FieldTool.in("java.lang.Integer").MAX_VALUE)

Json Tool

The Json Tool allows you to consume remote JSON resources and work with the resulting data in Velocity.

Json Tool methods.
Method Parameters Return Type Description
$_JsonTool.fetch(url) url (String) HashMap or ArrayList Fetches JSON from the given URL and returns it as a HashMap (for objects) or ArrayList (for arrays).
$_JsonTool.fetchWithApiKey(url, key) url (String), key (String) HashMap or ArrayList Fetches JSON from the given URL using the specified API key in the Authorization header.
Velocity
## Fetch a JSON API and iterate over results
#set ($data = $_JsonTool.fetch("https://api.example.com/items"))
#foreach ($item in $data)
  <p>$item.get("name")</p>
#end

List Tool

The List Tool performs common operations on lists and arrays.

List Tool methods.
Method Parameters Description
$_ListTool.removeNull(list, property) list (List), property (String) Removes items from the list that do not have the specified property or have a null value for it.
$_ListTool.reverse(list) list (List) Returns the list in reverse order.
$_ListTool.shuffle(list) list (List) Returns the list in a randomized order.
$_ListTool.toList(array) array (Array) Converts an array to a list.

Math Tool

The Math Tool provides mathematical operations and number conversions. Added in 6.10

Math Tool methods.
Method Parameters Description
$_MathTool.abs(n) n (Number) Returns the absolute value.
$_MathTool.add(a, b) a (Number), b (Number) Returns the sum of two numbers.
$_MathTool.ceil(n) n (Number) Rounds up to the nearest integer.
$_MathTool.div(a, b) a (Number), b (Number) Returns the result of division.
$_MathTool.floor(n) n (Number) Rounds down to the nearest integer.
$_MathTool.getRandom() — Returns a random number between 0.0 and 1.0.
$_MathTool.idiv(a, b) a (Number), b (Number) Returns the result of integer division.
$_MathTool.max(a, b) a (Number), b (Number) Returns the greater of two numbers.
$_MathTool.min(a, b) a (Number), b (Number) Returns the lesser of two numbers.
$_MathTool.mod(a, b) a (Number), b (Number) Returns the modulus (remainder).
$_MathTool.mul(a, b) a (Number), b (Number) Returns the product of two numbers.
$_MathTool.pow(a, b) a (Number), b (Number) Returns the first number raised to the power of the second.
$_MathTool.random(a, b) a (Number), b (Number) Returns a random number between the two specified numbers.
$_MathTool.round(n) n (Number) Rounds to the nearest integer.
$_MathTool.roundTo(places, n) places (int), n (Number) Rounds to the specified number of decimal places.
$_MathTool.sub(a, b) a (Number), b (Number) Returns the difference of two numbers.
$_MathTool.toDouble(n) n (Object) Converts the value to a Double.
$_MathTool.toInteger(n) n (Object) Converts the value to an Integer.
$_MathTool.toNumber(n) n (Object) Converts the value to a Number.

Number Tool

The Number Tool formats numeric data for display. Added in 6.10

Number Tool methods.
Method Parameters Description
$_NumberTool.currency(n) n (Number) Formats the number as currency (e.g. $1,234.56).
$_NumberTool.format(pattern, n) pattern (String), n (Number) Formats the number using the specified pattern.
$_NumberTool.integer(n) n (Number) Formats the number as an integer.
$_NumberTool.isNumeric(value) value (Object) Returns true if the value can be parsed as a number.
$_NumberTool.number(n) n (Number) Formats as a number with grouping separators.
$_NumberTool.percent(n) n (Number) Formats the number as a percentage.
$_NumberTool.toNumber(text) text (String) Parses a formatted number string back into a Number object.
$_NumberTool.withPadding(n, width) n (Number), width (int) Pads the number with leading zeros to the specified width.
$_NumberTool.sortable(n) n (Number) Generates a string representation suitable for lexicographic sorting of numbers.

Property Tool

The Property Tool lets you inspect and evaluate object properties at runtime. Added in 7.4

Type checking

Property Tool type-checking methods.
Method Parameters Description
$_PropertyTool.isArray(obj) obj (Object) Returns true if the object is an array.
$_PropertyTool.isIterable(obj) obj (Object) Returns true if the object is iterable.
$_PropertyTool.isList(obj) obj (Object) Returns true if the object is a list.
$_PropertyTool.isMap(obj) obj (Object) Returns true if the object is a map.
$_PropertyTool.isSet(obj) obj (Object) Returns true if the object is a set.
$_PropertyTool.isString(obj) obj (Object) Returns true if the object is a string.

Value checking

Property Tool value-checking methods.
Method Parameters Description
$_PropertyTool.isEmpty(obj) obj (Object) Returns true if the object is null, empty, or whitespace-only.
$_PropertyTool.isNotEmpty(obj) obj (Object) Returns true if the object is not null or empty.
$_PropertyTool.isNull(obj) obj (Object) Returns true if the object is null.
$_PropertyTool.isNotNull(obj) obj (Object) Returns true if the object is not null.

Output methods

Property Tool output methods.
Method Parameters Description
$_PropertyTool.outputFirstNotEmpty(values) values (Object...) Returns the first value that is not empty from the given arguments.
$_PropertyTool.outputProperties(obj) obj (Object) Lists all available properties and methods on the object. Useful for debugging.

Regex Tool

The Regex Tool allows you to work with regular expressions in Velocity. Added in 8.16

Regex Tool methods.
Method Parameters Return Type Description
$_RegexTool.compile(pattern) pattern (String) Pattern Compiles a regular expression string into a Pattern object for matching and replacement operations.
Velocity
## Compile a regex and use it for matching
#set ($pattern = $_RegexTool.compile("[0-9]+"))
#set ($matcher = $pattern.matcher("Order 12345"))
#if ($matcher.find())
  Order number: $matcher.group()
#end

Serializer Tool

The Serializer Tool converts JDOM Elements to XML strings or JSON. Added in 6.2

Serializer Tool methods.
Method Parameters Return Type Description
$_SerializerTool.serialize(element) element (Element) String Converts a JDOM Element to an XML string.
$_SerializerTool.toJson(input) input (Element, String, or Map) String Converts an Element, XML string, or Map to a JSON string.
Velocity
## Convert the page's XML to a JSON string
#set ($json = $_SerializerTool.toJson($contentRoot))
<script>
  var pageData = $json;
</script>

Sort Tool

The Sort Tool sorts lists of JDOM Elements with support for multiple sort criteria. Added in 6.2

Sort Tool methods.
Method Parameters Description
$_SortTool.addSortCriterion(xpath, language, dataType, order, caseOrder) xpath (String), language (String), dataType (String), order (String), caseOrder (String) Configures a sort criterion. dataType can be text or number. order can be ascending or descending. caseOrder can be upper-first or lower-first.
$_SortTool.sort(list) list (List) Returns the list sorted according to the configured criteria.

String Tool

The String Tool provides methods for finding and extracting content within strings. Added in 6.2

String Tool methods.
Method Parameters Return Type Description
$_StringTool.generateUUID() — String Generates a random UUID string.
$_StringTool.getStringBuilder() — StringBuilder Returns a new StringBuilder instance for building strings efficiently.
$_StringTool.substringAfter(text, needle) text (String), needle (String) String Returns the portion of the string after the first occurrence of the needle.
$_StringTool.substringBefore(text, needle) text (String), needle (String) String Returns the portion of the string before the first occurrence of the needle.

XPath Tool

The XPath Tool queries JDOM XML trees using XPath expressions. Added in 6.2

XPath Tool methods.
Method Parameters Return Type Description
$_XPathTool.selectNodes(xpath, element) xpath (String), element (Element) List Returns a list of nodes matching the XPath expression.
$_XPathTool.selectSingleNode(xpath, element) xpath (String), element (Element) Object Returns the first node matching the XPath expression.
Velocity
## Select all "item" elements from the content XML
#set ($items = $_XPathTool.selectNodes("//item", $contentRoot))
#foreach ($item in $items)
  <p>$item.getChildText("title")</p>
#end

## Select a single element
#set ($header = $_XPathTool.selectSingleNode("/system-data-structure/header", $contentRoot))
$header.text