Template Context
Context Variables
These variables are accessible directly in the Variables section in the Template tab. Confluence will provide values for them when rendering is performed. So, each user variable $user will have its own value. The same goes for page and space, depending on where the macro is added.
Current User
Velocity context has an object $user representing the user viewing the page with the installed macro. Using the $user object, the following fields can be accessible:
Public name —
$user.publicNameProfile picture URI —
$user.profilePicture.pathGroups membership —
$user.groups…
The full user object structure is described below:
{
"type": <string>,
"accountId": <string>,
"accountType": <string>,
"email": <string>,
"publicName": <string>,
"profilePicture": {
"path": <string>,
"width": <integer>,
"height": <integer>,
"isDefault": <boolean>
},
"displayName": <string>,
"isExternalCollaborator": <boolean>,
"isGuest": <boolean>,
"_expandable": {
"operations": <string>,
"personalSpace": <string>
},
"_links": {
"self": <string>,
"base": <string>,
"context": <string>
},
"groups": [
{
"type": "group",
"name": <string>,
"id": <string>
},
{
"type": "group",
"name": <string>,
"id": <string>
}
]
}
Current Page
Velocity context has an object $page representing the page with installed macro. Using the $page object, the following fields can be accessible:
Title —
$page.titleSpace id —
$page.spaceIdVersion number —
$page.version.number…
The full page object structure is described below:
{
"ownerId": <string>,
"position": <integer>,
"version": {
"number": <integer>,
"message": <string>,
"minorEdit": <boolean>,
"authorId": <string>,
"createdAt": <string>
},
"body": {},
"status": <string>,
"title": <string>,
"createdAt": <string>,
"authorId": <string>,
"spaceId": <string>,
"id": <string>,
"_links": {
"editui": <string>,
"webui": <string>,
"edituiv2": <string>,
"tinyui": <string>
}
}
Current Space
Velocity context has an object $space representing the space of a page with installed macro. Using the $space object, the following fields can be accessible:
Name —
$space.nameId —
$space.idDescription —
$space.description…
Full space object structure is described below:
{
"createdAt": <string>,
"authorId": <string>,
"homepageId": <string>,
"description": {},
"status": <string>,
"name": <string>,
"key": <string>,
"id": <string>,
"type": <string>,
"_links": {
"webui": <string>,
"base": <string>
}
}
BaseUrl
Context holds value for the base URL of the Confluence instance:
$baseUrl
The render result will be the following:https://{host}.atlassian.net/wiki
RenderMode
Context holds value for rendering type
$renderMode
In Confluence Cloud there are 4 render modes available:
word — default Confluence Word export
pdf — default Confluence PDF export
email — default Confluence email notification
default — third-party apps export
#if(!$renderMode) ## Render mode is empty
Page in view mode
#elseif($renderMode.equals("pdf") || $renderMode.equals("word"))
Document export
#elseif($renderMode.equals("email"))
Email
#elseif($renderMode.equals("default"))
Third-party app export
#end
Macro id
Context holds value for macro installation id. MacroId is provided in form of macroExternalId from HTTP request from Atlassian.
$macroId
It’s a unique identifier of the macro on the page. So, duplicated macros on the page will still have different $macroId. It might be useful to store macro state in the page properties.
Macro Content
Body
Context holds value for the body: $body. This variable is available only if Body Type (more: macro body types) is set to Plain Text or Rich Text.
In those modes, the body will be rendered by Confluence, which allows the use of nested macros on the page.
Parameters
Context holds value for parameters. Value for a parameter is set when adding or editing a macro on the page.
Can be accessed: $parameters.{key}or $parameters.["key"]
Context Utils
String Utils
The StringUtils class from the Apache Commons Lang library is a utility class designed to simplify common string manipulations in Java. It provides a variety of static methods to handle tasks such as:
Filtering if parameter value contains one of user`s group
#set($filterValue = $parameters.groups) #set($group = $user.groups[0].name) $StringUtils.contains($filterValue. $group))
Checking if current user is author of page
$StringUtils.equals($user.accountId, $page.authorId))
Splitting groups from parameter input using comma
$StringUtils.split($parameters.groups, ",")
Bringing label from parameter`s input to lower or upper case
$StringUtils.lowerCase($parameters.label)) $StringUtils.upperCase($parameters.label))
Trimming strings like page title
$StringUtils.trim($page.title)
Creating base url for Jira (both works the same way)
$StringUtils.replace($baseUrl,"/wiki","")) $StringUtils.remove($baseUrl, "/wiki"))
Getting creation date without time
$StringUtils.substringBefore($page.createdAt, "T") ## Result format: YYYY-MM-DD
More posibilities listed under official documentation of StringUtils.
Number Utils
The NumberUtils class from the Apache Commons Lang library offers a suite of static utility methods designed to simplify operations involving Java's Number classes. These methods facilitate tasks such as number conversion, comparison, and validation, streamlining numerical operations in Java applications.
Validating User Input
#set ( $userInput1 = "123.45") #set ( $userInput2 = "123.45abc") $NumberUtils.isParsable($userInput1); ## Result: true $NumberUtils.isParsable($userInput2); ## Result: false
Converting Strings to Numbers with Default Values
#set ( $invalidInput = "invalid") #set ( $validInput = "123") $NumberUtils.toInt($invalidInput, -1) ## Result: -1 $NumberUtils.toInt($validInput, -1) ## Result: 123
Finding Maximum and Minimum in Arrays(THIS PROBABLY NEEDS TO BE REPLACED)
int[] numbers = {5, 3, 9, 1, 4}; int max = NumberUtils.max(numbers); // Result: 9 int min = NumberUtils.min(numbers); // Result: 1Handling Different Number Formats
#set ( $hexNUmber = "0x1A" ) #set ( $scientificNumber = "1.23e4" ) $NumberUtils.createInteger($hexNumber) ## Result: 26 $NumberUtils.createDouble($scientificNumber) ## Result: 12300.0
Checking for Digits Only
#set ( $input1 = "123456") #set ( $input2 = "123456abc") $NumberUtils.isDigits($input1) ## Result: true $NumberUtils.isDigits($input2) ## Result: false
More possibilities available NumberUtils.
Collection Utils
Combining Two Lists of pages from different spaces
#set($spaces=$ConfluenceManager.get("/wiki/api/v2/spaces").results) #set($pages1=$ConfluenceManager.get("/wiki/api/v2/spaces/${spaces[0].id}/pages").results) #set($pages2=$ConfluenceManager.get("/wiki/api/v2/spaces/${spaces[1].id}/pages").results) $CollectionUtils.union($pages1,$pages2)Checking if the author is an admin
#set ( $adminGroups = ["confluence-admins", "site-admins", "administrators"]) #set ( $authorGroups = []) #set($groups=$ConfluenceManager.get("/wiki/rest/api/user/memberof?accountId=${page.authorId}").results) #foreach ( $group in $groups ) #set ( $noprint = $authorGroups.add($group.name)) #end $CollectionUtils.containsAny($authorGroups,$adminGroups)Finding common groups for author and owner of page
#set($authorGroups=$ConfluenceManager.get("/wiki/rest/api/user/memberof?accountId=${page.authorId}").results) #set($ownerGroups=$ConfluenceManager.get("/wiki/rest/api/user/memberof?accountId=${page.ownerId}").results) $CollectionUtils.intersection($ownerGroups,$authorGroups)
More posibilities listed under official documentation of CollectionUtils.
Date Utils
The DateUtils class from Apache Commons Lang provides a comprehensive set of utility methods for manipulating and formatting dates and times in Java. It simplifies common date operations such as adding or subtracting time units, truncating dates, and comparing dates. User Macro provides some additional methods (isWithinLastDays,isBetweenDates, isAfterDate, isBeforeDate) to DateUtils for more convinient work with default format of dates for confluence objects: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
Parsing a Date String
#set ($pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #set ($format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") $DateUtils.parseDate($page[0].createdAt, $format) ## Result format: Wed Jul 12 07:16:05 UTC 2023Adding Days to a Date
#set ($pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #set ($format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") #set ($date = $DateUtils.parseDate($page[0].createdAt, $format)) $DateUtils.addDays($date, 5); ## Result format: Mon Jul 17 07:16:05 UTC 2023;Checking if Two Dates Are on the Same Day
#set ($pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #set ($format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") #set ($date1 = $DateUtils.parseDate($pages[0].createdAt, $format)) #set ($date2 = $DateUtils.parseDate($pages[1].createdAt, $format)) $DateUtils.isSameDay($date1, $date2) ## Result format: booleanCalculating the Number of Days Between Two Dates
#set ($pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #set ($format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") #set ($date1 = $DateUtils.parseDate($pages[0].createdAt, $format)) #set ($date2 = $DateUtils.parseDate($pages[1].createdAt, $format)) #set ($diffInMillies = $date2.getTime() - $date1.getTime()) #set ($diffInDays = $diffInMillies / (1000 * 60 * 60 * 24)) $diffInDays
More posibilities listed under official documentation of DateUtils.
DateUtils custom methods
DateUtils has many useful , but we added these!!!!
IsWithinLastDays(String createdAt, int numberOfDays)
$DateUtils.isWithinLastDays($page.createdAt,100)
isBetweenDates(String dateToCheck, String startDate, String endDate)
#set($pages=$ConfluenceManager.get("/wiki/api/v2/pages").results) $DateUtils.isBetweenDates($pages[0].createdAt, $pages[1].createdAt, $pages[2].createdAt)isAfterDate(String dateToCheck, String startDate)
$DateUtils.isAfterDate($page.createdAt, $page.version.createdAt)
isBeforeDate(String dateToCheck, String startDate)
$DateUtils.isBeforeDate($page.createdAt, $page.version.createdAt)
Sort Tool
The CollectionTool class in Apache Velocity Tools provides utility methods for sorting collections (such as lists, arrays, or iterators) based on specified properties of the objects they contain. This functionality is particularly useful within a #foreach loop in Velocity templates, allowing for dynamic and flexible data presentation. Velocity context holds this class under $SortTool to avoid confusing with $CollectionUtils.
Single Property Sort
#set ($groups = $ConfluenceManager.get("/wiki/rest/api/group").results) #foreach ( $group in $SortTool.sort($groups, "name")) <li>$group.name</li> #endMultiple Property Sort
#set ( $pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #foreach ( $page in $SortTool.sort($pages, ["title","status"])) <li>$page.title - $page.status</li> #endSorting with Ascending and Descending Order
#set ( $pages = $ConfluenceManager.get("/wiki/api/v2/pages").results) #foreach ( $page in $SortTool.sort($pages, ["title:desc","status:asc"])) <li>$page.title - $page.status</li> #end
More posibilities listed under official documentation of CollectionTools.
Math Tool
The MathTool in Apache Velocity is a utility class that facilitates mathematical operations within Velocity templates. It supports basic method like these:
$MathTool.add(5, 10) ## Addition result: 15 $MathTool.sub(10, 5) ## Subtraction result: 5 $MathTool.mul(10, 5) ## Multiplication result: 50 $MathTool.div(10, 5) ## Division result: 2
MathTool can be useful when working with confluence content, for example:
Getting average number of pages across all spaces.
#set($pagesCount = [])
#foreach ($space in $ConfluenceManager.get("/wiki/api/v2/spaces").results )
#set ($pageCount = $ConfluenceManager.get("/wiki/api/v2/spaces/${space.id}/pages").results.size())
## Need to set value in order to not print result of adding object to array
#set($ignore = $pagesCount.add($pageCount))
#end
## Average without rounding
$MathTool.getAverage($pagesCount)
## Average with rounding
$MathTool.round($MathTool.getAverage($pagesCount))
More posibilities listed under official documentation of MathTools.
Context HTTP service
ConfluenceManager
User Macro provides access to Confluence REST API both v1 and v2 via object ConfluenceManager.
Due to limitations this manager allows user to make only GET request. All of the endpoints from REST API are displayed the same way as in the documentation and are duplicated in the Helpers section when editing template. It can help with various task like:
Getting all spaces
$ConfluenceManager.get("/wiki/api/v2/spaces?type=global&limit=250&include-icon=true")Getting page author
$ConfluenceManager.get("/wiki/rest/api/user?accountId=$page.authorId")Getting attachments for space
#set( $query = "type=attachment and space=${space.key}" ) #set( $expand = "extensions,version" ) #set( $url = "/wiki/rest/api/content/search?limit=250&expand=${expand}&cql=${query}") $ConfluenceManager.get($url).results
JiraManager
User Macro provides access to Jira REST API via object JiraManager. Due to limitations this manager allows user to make only GET request. All of the endpoints from REST API are displayed the same way as in the documentation and are duplicated in the Helpers section when editing template. It can help with various task like:
Getting issues assigned to current user
$JiraManager.get("/rest/api/3/search/jql?jql=assignee = currentUser()")Getting transitions for issue
#set ( $issueId = $JiraManager.get("/rest/api/3/search/jql?jql=assignee = currentUser()").issues[0].id ) $JiraManager.get("/rest/api/3/issue/${issueId}/transitions")Getting worklogs for issues
#set ( $issueId = $JiraManager.get("/rest/api/3/search/jql?jql=assignee = currentUser()").issues[0].id ) $JiraManager.get("/rest/api/3/issue/${issueId}/worklog")
RequestManager
Request manager is a helper that can be used to make GET request to any public API.
$RequestManager.get("https://dummyjson.com/products/1")