> ## Documentation Index
> Fetch the complete documentation index at: https://learn.nextedy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Velocity Template Context

> Nextedy RISKSHEET uses Apache Velocity templates for the top panel, PDF export scripts, and (since v25.4.0) the sheet configuration.

export const LastReviewed = ({date}) => {
  if (!date) return null;
  const formatted = new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    timeZone: "UTC"
  });
  return <p className="mt-10 text-sm text-gray-400 dark:text-zinc-500 not-prose">
      Last reviewed on {formatted}
    </p>;
};

<Frame>
  <img src="https://mintcdn.com/none-17b4493f/yWl5nA2D0IzEnZC1/risksheet/diagrams/reference/api/velocity-context/diagram-1.svg?fit=max&auto=format&n=yWl5nA2D0IzEnZC1&q=85&s=5c1024b20411cf8a00e7150f1ad55fc0" alt="diagram" style={{ maxWidth: "580px", width: "100%" }} width="580" height="220" data-path="risksheet/diagrams/reference/api/velocity-context/diagram-1.svg" />
</Frame>

## Context Availability

| Template                                           | Velocity Context Available | Notes                                                             |
| -------------------------------------------------- | -------------------------- | ----------------------------------------------------------------- |
| `risksheetTopPanel.vm` (top panel configuration)   | Yes                        | Full context with Polarion services, document, and Velocity tools |
| `risksheetPdfExport.vm` (PDF export configuration) | Yes                        | Full context plus `pdfExportMacros.vm` helpers                    |
| Sheet configuration                                | Yes (since v25.4.0)        | Velocity expressions evaluated during configuration parsing       |

<Tip title="Dynamic Configuration">
  Since version 25.4.0, the Velocity context is also available in the sheet configuration. This enables dynamic configuration values driven by Polarion services such as `$repositoryService`.
</Tip>

## Document Objects

| Variable       | Type            | Description                                                              |
| -------------- | --------------- | ------------------------------------------------------------------------ |
| `$document`    | Polarion Module | The current Polarion document (module) object                            |
| `$doc`         | Polarion Module | Alias for `$document`, provides access to document API                   |
| `$transaction` | Transaction     | Current Polarion transaction for data operations                         |
| `$item`        | Work Item       | Current work item context (available in `serverRender` column templates) |

### Accessing Document Custom Fields

Use `$document.customFields` to read document-level custom fields in the top panel.

```velocity theme={null}
## Display a document custom field in the top panel
<div>Product Family: $document.customFields.productFamily</div>
```

Use `$doc.getOldApi().getValue('customFieldID')` for programmatic access to custom field values.

```velocity theme={null}
## Access custom field via Old API
#set($riskAcceptance = $doc.getOldApi().getValue("riskAcceptanceMatrix"))
<script>
  var riskMatrix = "$riskAcceptance";
</script>
```

<Note title="Read-Only Access">
  The top panel can display document custom fields using Velocity but cannot currently modify them. Custom field modification requires Polarion's standard document editing interface.
</Note>

## Polarion Services

| Variable                 | Type                    | Description                                                                    |
| ------------------------ | ----------------------- | ------------------------------------------------------------------------------ |
| `$repositoryService`     | Repository Service      | Access to Polarion repository operations for querying work items and documents |
| `$securityService`       | Security Service        | Returns the current user and role membership (top panel)                       |
| `$testManagementService` | Test Management Service | Retrieves test execution records for a work item (`serverRender`)              |

### `$securityService` — Current User and Roles

Available in `risksheetTopPanel.vm`. Provides identity information for role-based UI logic such as conditional rendering or per-role default views.

```velocity theme={null}
## Resolve current user and their Polarion roles
#set($user = $securityService.getCurrentUser())
#set($roles = $securityService.getRolesForUser($user))
<script>
  var currentUser = "$user";
  var userRoles = "$roles";
  // Example: load a different default saved view for reviewers
  if (userRoles.indexOf("reviewer") !== -1) {
    risksheet.appConfig.views[2].defaultView = true;
  }
</script>
```

### `$testManagementService` — Test Execution Records

Available in `serverRender` column templates. Use it to surface the latest test execution outcome next to a risk item or requirement.

```velocity theme={null}
## Get last test execution result for the current work item
#macro(getLastTestRecord $item)
  #set($testRecords = $testManagementService.getLastTestRecords($item.getOldApi(), 1))
  #foreach($iRecord in $testRecords)
    #set($testRun = $transaction.testRuns().getBy().oldApiObject($iRecord.getTestRun()))
    $iRecord.getTestRun().getId() - $iRecord.getResult().name
  #end
#end
#getLastTestRecord($item)
```

The complete list of Polarion services in the Velocity context depends on your Polarion version and Risksheet release. Verify availability in your deployment.

## Top Panel Context

The top panel Velocity template (`risksheetTopPanel.vm`) renders HTML above the Risksheet grid via the `/api/panel` endpoint. The template has full access to Polarion services and document context.

<Frame>
  <img src="https://mintcdn.com/none-17b4493f/yWl5nA2D0IzEnZC1/risksheet/diagrams/reference/api/velocity-context/diagram-2.svg?fit=max&auto=format&n=yWl5nA2D0IzEnZC1&q=85&s=94e5bb5a1b62f1bc5b7b6fca056c9206" alt="diagram" style={{ maxWidth: "580px", width: "100%" }} width="580" height="310" data-path="risksheet/diagrams/reference/api/velocity-context/diagram-2.svg" />
</Frame>

### Bridging Top Panel Functions to Formulas

JavaScript functions defined in the top panel `<script>` block can be called from formulas in the sheet configuration.

```velocity theme={null}
## In risksheetTopPanel.vm
#set($matrixData = $doc.getOldApi().getValue("riskAcceptanceMatrix"))
<script>
  function getRiskAcceptance(severity, occurrence) {
    var matrix = JSON.parse('$matrixData');
    return matrix[severity][occurrence];
  }
</script>
```

```yaml theme={null}
formulas:
  riskAcceptance: "function(info) { return getRiskAcceptance(info.item['severity'], info.item['occurrence']); }"
```

### Referencing External Data Sources

The top panel can reference external data sources via Velocity context and Polarion APIs, enabling dynamic risk matrix definitions shared across projects.

```velocity theme={null}
## Load risk matrix from external XML configuration
#set($avasisConfig = $repositoryService.getConfigurationService().getXmlConfig("avasis"))
<script>
  var dynamicMatrix = $avasisConfig.toJson();
</script>
```

## PDF Export Context

The PDF export Velocity template (`risksheetPdfExport.vm`) receives the full Velocity context plus helper macros.

| Additional Context   | Description                                                     |
| -------------------- | --------------------------------------------------------------- |
| `pdfExportMacros.vm` | Helper macros for PDF-specific formatting and layout            |
| `revision` parameter | Required parameter specifying which document revision to export |

See [PDF Export Template](/risksheet/reference/templates/pdf-export-template) for template structure and [PDF Export API](/risksheet/reference/api/pdf-export-api) for the JavaScript export methods.

## Sheet Configuration Context

Since version 25.4.0, Velocity expressions in the sheet configuration are evaluated during configuration loading. This enables dynamic values for project references, document fields, and conditional configuration.

```yaml theme={null}
dataTypes:
  task:
    type: $velocityExpression
```

The exact Velocity expressions supported in the sheet configuration and their evaluation order should be verified against your Risksheet version. Not all configuration properties may support Velocity evaluation.

## Error Handling

| Scenario                 | Behavior                                              |
| ------------------------ | ----------------------------------------------------- |
| Template rendering error | Red error message box displayed in place of the panel |
| Missing template file    | Default empty panel rendered                          |
| Velocity syntax error    | Error details rendered as HTML in the panel area      |

## Related Pages

* [Velocity Templates](/risksheet/reference/templates/velocity-templates) for template file reference
* [Top Panel Template](/risksheet/reference/templates/top-panel-template) for top panel template structure
* [PDF Export Template](/risksheet/reference/templates/pdf-export-template) for PDF export template structure
* [PDF Export API](/risksheet/reference/api/pdf-export-api) for JavaScript export methods
* [Formula Syntax](/risksheet/reference/formulas/formula-syntax) for formula expressions that can call top panel functions
* [Configuration Properties Index](/risksheet/reference/configuration/properties-index) for configuration reference

<LastReviewed date="2026-06-08" />
