Template Context Reference - Facet SSR Framework
All variables available in Pebble templates
Complete reference for all variables available in Facet templates.
Table of Contents
- Global Context Variables
- Authentication Context
- MongoDB Request Context
- Pagination Context
- Permission Context
- Multi-Tenant Context
- Generic JSON Service Context
- Error Page Context
- Enriched Items Structure
- Common Patterns
- Custom Pebble Filters
Global Context Variables
These variables are available in all templates throughout the application, error pages included. They are set during plugin initialization and remain constant during the application lifecycle.
| Variable | Type | Description | Example |
|---|---|---|---|
version |
String | RESTHeart version number ("unknown" if not available) |
"9.12.3" |
buildTime |
String | RESTHeart build timestamp | "2026-10-28T23:56:00Z" |
mongoPrefix |
String | MongoDB mount prefix: the where of the first mongo-mounts entry, normalized with a leading slash and no trailing slash; "/" when MongoDB is mounted at the root. Set by html-response-interceptor |
"/", "/api", "/data" |
loginUrl |
String | Login page URL (the uri of login-service). Set only when login-service is enabled |
"/login" |
rolesUrl |
String | Roles endpoint URL (roles-endpoint of login-service, default /roles). Set only when login-service is enabled |
"/roles" |
Usage Example
<footer>
<p>RESTHeart v{{ version }} - Built {{ buildTime }}</p>
<a href="{{ loginUrl }}">Login</a>
</footer>
Authentication Context
These variables are conditionally set based on whether a user is authenticated.
| Variable | Type | Description | When Set |
|---|---|---|---|
isAuthenticated |
Boolean | Whether user is authenticated | Always |
username |
String | Authenticated user's principal name | If authenticated |
roles |
Set<String> | User's role names | If authenticated |
requestMethod |
String | HTTP method of the current request | Always |
isHtmxRequest |
Boolean | Whether the request was sent by HTMX (HX-Request: true) |
Always |
requestMethod values: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, OTHER
Use requestMethod to show post-mutation feedback in templates:
{% if requestMethod == "POST" %}
<div class="alert success">Created successfully!</div>
{% endif %}
Usage Example
{% if isAuthenticated %}
<p>Welcome, {{ username }}!</p>
{% if roles contains "admin" %}
<a href="/admin">Admin Panel</a>
{% endif %}
<!-- Logout is a POST to RESTHeart's authCookieRemover (/logout) -->
<button onclick="fetch('/logout', { method: 'POST', credentials: 'include' }).then(() => location.href = '{{ loginUrl }}')">Logout</button>
{% else %}
<a href="{{ loginUrl }}">Login</a>
{% endif %}
MongoDB Request Context
These variables provide information about the current MongoDB request and resource.
Path Variables
| Variable | Type | Description | Example |
|---|---|---|---|
path |
String | Full request path including prefix | "/api/mydb/products" |
mongoPath |
String | Request path with mongoPrefix stripped (on segment boundaries: /api does not strip /apidocs) and no trailing slash |
"/mydb/products" |
resourceUrl |
String | Canonical MongoDB resource path (/db/coll/docId, no mount prefix), resolved from mongo-mounts |
"/mydb/products" |
collectionUrl |
String | Like resourceUrl, with the document id removed on document requests (no mount prefix) |
"/mydb/products" |
Resource Identification
| Variable | Type | Description | Example |
|---|---|---|---|
resourceType |
Enum (ExchangeKeys.TYPE) |
Type of MongoDB resource; renders and compares as its name | "ROOT", "DB", "COLLECTION", "DOCUMENT" |
db |
String | Current database name (resolved from mount or request) | "mydb" |
coll |
String | Current collection name (resolved from mount or request) | "products" |
Note: db and coll are the resolved values, accounting for parametric mounts. Templates no longer need to check both mounted and non-mounted versions. db, coll, resourceUrl, collectionUrl and the permission flags are set only when RESTHeart provides the resolved mount context.
Data Variables
| Variable | Type | Description |
|---|---|---|
items |
List<Map> | List of enriched items (databases, collections, or documents) |
data |
List<String> | The response as JSON strings, one per item (pretty-printed; documents with a non-ObjectId _id get an extra __id_type__ field) |
Note: The items list contains different types depending on resourceType:
ROOT: Database namesDB: Collection namesCOLLECTION: DocumentsDOCUMENT: Single document
See Enriched Items Structure for details.
Query Parameters
| Variable | Type | Description | Default |
|---|---|---|---|
filter |
String | MongoDB query filter (JSON) | "" (empty string) |
keys |
String | MongoDB field projection/keys (JSON) | "" (empty string) |
sort |
String | MongoDB sort specification (JSON) | "" (empty string) |
Usage Example
<h1>
{% if resourceType == 'ROOT' %}
Databases
{% elseif resourceType == 'DB' %}
Collections in {{ db }}
{% elseif resourceType == 'COLLECTION' %}
Documents in {{ db }}.{{ coll }}
{% elseif resourceType == 'DOCUMENT' %}
Document in {{ db }}.{{ coll }}
{% endif %}
</h1>
{% if filter %}
<p>Filtered by: <code>{{ filter }}</code></p>
{% endif %}
Pagination Context
Variables for paginated results.
| Variable | Type | Description | Example |
|---|---|---|---|
page |
int | Current page number (1-indexed) | 1 |
pagesize |
int | Number of items per page | 25 |
totalPages |
int | Total number of pages (at least 1) | 10 |
totalItems |
long | Total item count | 237 |
Usage Example
<div class="pagination">
<p>Page {{ page }} of {{ totalPages }} ({{ totalItems }} total items)</p>
{% if page > 1 %}
<a href="?page={{ page - 1 }}&pagesize={{ pagesize }}">Previous</a>
{% endif %}
{% if page < totalPages %}
<a href="?page={{ page + 1 }}&pagesize={{ pagesize }}">Next</a>
{% endif %}
</div>
Permission Context
Boolean flags indicating which operations the MongoDB mount allows. They are derived from the mongo-mounts configuration, not from the user's ACL permissions: hide or show UI with them, but authorization is still enforced by RESTHeart.
| Variable | Type | Description |
|---|---|---|
canCreateDatabases |
Boolean | Can create new databases |
canCreateCollections |
Boolean | Can create new collections |
canCreateDocuments |
Boolean | true on collection requests (a collection is set and the request is not for a single document) |
canDeleteDatabase |
Boolean | Can delete current database |
canDeleteCollection |
Boolean | Can delete current collection |
Usage Example
{% if canCreateDocuments %}
<button onclick="showCreateDialog()">Create Document</button>
{% endif %}
{% if canDeleteCollection %}
<button onclick="deleteCollection()">Delete Collection</button>
{% endif %}
Multi-Tenant Context
Variables for multi-tenant deployments using parametric mounts.
| Variable | Type | Description | Example |
|---|---|---|---|
tenantId |
String | Plain tenant identifier, or null when none was resolved |
"acme", null |
isMultiTenant |
Boolean | true when the mount has parametric mounts and a tenant id was resolved |
true, false |
hostParams |
String | Hostname parameters as a JSON string ("{}" without a Host header) |
{"host":"acme.example.com","host[0]":"acme"} |
Since 1.1.0 tenantId is no longer a JSON-quoted string, so {% if tenantId %} works. To embed it in JavaScript, serialize it: {{ tenantId | toJson | raw }}.
Usage Example
{% if isMultiTenant %}
<div class="tenant-banner">
<p>Tenant: {{ tenantId }}</p>
</div>
{% endif %}
Generic JSON Service Context
For non-MongoDB JSON services (JavaScript plugins and custom services).
| Variable | Type | Description |
|---|---|---|
path |
String | Request path |
data |
String | Raw JSON response body ("{}" when empty) |
isAuthenticated, username, roles, requestMethod, isHtmxRequest |
Same as in the Authentication Context | |
| (dynamic) | Various | All top-level keys of a JSON object response merged into context (nothing is merged for arrays or non-JSON bodies) |
Facet's own variables (isAuthenticated, username, roles, requestMethod, path, data) always win over same-named fields of the service response (since 1.1.0): a service that needs a field with one of those names must rename it. JSON numbers are parsed as doubles, so 42 renders as 42.0; use numberformat to format them.
Usage Example
<!-- For a service returning: {"status": "ok", "count": 42} -->
<p>Status: {{ status }}</p>
<p>Count: {{ count | numberformat("#") }}</p>
<!-- Raw JSON access -->
<pre>{{ data }}</pre>
Error Page Context
Error templates (templates/errors/{code}.html or templates/error.html) receive the global variables plus:
| Variable | Type | Description |
|---|---|---|
statusCode |
int | HTTP status code |
statusMessage |
String | HTTP status text (e.g. "Not Found") |
path |
String | Request path |
username |
String | Authenticated user's principal name, null if not authenticated |
Enriched Items Structure
The items list contains enriched objects with additional metadata for navigation and rendering.
For Database/Collection Names (Simple Strings)
{
"value": "products", // The database or collection name
"isString": true // Flag indicating this is a simple string value
}
For Documents (BSON Objects)
{
"data": Map, // Full document as a plain map (ObjectId → hex string, dates → epoch millis)
"isString": false, // Flag indicating this is a document
"_id": { // ID metadata for URL generation
"value": "507f1f77bcf86cd799439011", // String representation of _id
"type": null, // ID type: null (ObjectId), "STRING", "NUMBER", etc.
"needsParam": false // Whether id_type query param is needed in URLs
} // "_id" is absent if the document has no _id
}
ID Type Detection
The _id.type field helps generate correct URLs:
null: MongoDB ObjectId (no query param needed)"STRING": String_id(needs?id_type=STRING); also used for other types such as binary, arrays and embedded documents"NUMBER": Numeric_id(int, long, double, decimal; needs?id_type=NUMBER)"BOOLEAN","DATE","NULL","MINKEY","MAXKEY": the corresponding BSON types
Usage Example
{% for item in items %}
{% if item.isString %}
<!-- Database or collection name -->
<li><a href="{{ path }}/{{ item.value }}">{{ item.value }}</a></li>
{% else %}
<!-- Document -->
<li>
<a href="{{ path }}/{{ item._id.value }}{% if item._id.needsParam and resourceType == 'COLLECTION' %}?id_type={{ item._id.type }}{% endif %}">
{{ item._id.value }}
</a>
<p>{{ item.data.name }}</p>
</li>
{% endif %}
{% endfor %}
Common Patterns
Building Navigation Links
<!-- Breadcrumb navigation -->
{% set prefix = mongoPrefix == '/' ? '' : mongoPrefix %}
{% set segments = mongoPath | split('/') %}
<nav>
<a href="{{ prefix }}/?page=1&pagesize={{ pagesize }}">Home</a>
{% set currentPath = prefix %}
{% for segment in segments %}
{% if segment != '' %}
{% set currentPath = currentPath ~ '/' ~ segment %}
/ <a href="{{ currentPath }}?page=1&pagesize={{ pagesize }}">{{ segment }}</a>
{% endif %}
{% endfor %}
</nav>
Conditional Rendering by Resource Type
{% if resourceType == 'ROOT' %}
<h1>Databases</h1>
{% elseif resourceType == 'DB' %}
<h1>Collections in {{ db }}</h1>
{% elseif resourceType == 'COLLECTION' %}
<h1>Documents in {{ db }}.{{ coll }}</h1>
{% elseif resourceType == 'DOCUMENT' %}
<h1>Document {{ db }}.{{ coll }}</h1>
{% endif %}
Pagination with Preserved Query Parameters
<div class="pagination">
{% set baseQuery = "pagesize=" ~ pagesize %}
{% if filter %}{% set baseQuery = baseQuery ~ "&filter=" ~ (filter | urlencode) %}{% endif %}
{% if sort %}{% set baseQuery = baseQuery ~ "&sort=" ~ (sort | urlencode) %}{% endif %}
{% if page > 1 %}
<a href="?{{ baseQuery }}&page={{ page - 1 }}">Previous</a>
{% endif %}
<span>Page {{ page }} of {{ totalPages }}</span>
{% if page < totalPages %}
<a href="?{{ baseQuery }}&page={{ page + 1 }}">Next</a>
{% endif %}
</div>
Permission-Based UI
<div class="actions">
{% if resourceType == 'COLLECTION' and canCreateDocuments %}
<button onclick="createDocument()">New Document</button>
{% endif %}
{% if resourceType == 'DB' and canCreateCollections %}
<button onclick="createCollection()">New Collection</button>
{% endif %}
{% if resourceType == 'COLLECTION' and canDeleteCollection %}
<button onclick="deleteCollection()" class="danger">Delete Collection</button>
{% endif %}
</div>
Debug: View Context Variables
Pebble's _context cannot be serialized ({{ _context | toJson }} fails), so print the variables you need:
<!-- Only in development -->
{% if username == "admin" %}
<details>
<summary>Debug: Template Context</summary>
<pre>path={{ path }} mongoPath={{ mongoPath }} resourceType={{ resourceType }} db={{ db }} coll={{ coll }}</pre>
<pre>{{ items | toJson }}</pre>
</details>
{% endif %}
Custom Pebble Filters
Facet registers custom Pebble filters for path manipulation and data formatting.
stripTrailingSlash
Removes trailing slashes from paths while preserving the root path /.
{{ "/api/testdb/" | stripTrailingSlash }} {# → "/api/testdb" #}
{{ "/mydb" | stripTrailingSlash }} {# → "/mydb" (unchanged) #}
{{ "/" | stripTrailingSlash }} {# → "/" (root preserved) #}
buildPath(segment)
Appends a segment to a base path with proper / handling.
{{ "/api/testdb" | buildPath("mycoll") }} {# → "/api/testdb/mycoll" #}
{{ "/" | buildPath("testdb") }} {# → "/testdb" #}
{{ "" | buildPath("testdb") }} {# → "/testdb" #}
{{ "/api" | buildPath(segment="testdb") }} {# → "/api/testdb" (named argument) #}
Common pattern:
{% set basePath = path | stripTrailingSlash %}
<a href="{{ basePath | buildPath('new-resource') }}">Create New Resource</a>
parentPath
Returns the parent path by removing the last segment.
{{ "/api/testdb/docs/item123" | parentPath }} {# → "/api/testdb/docs" #}
{{ "/testdb/docs" | parentPath }} {# → "/testdb" #}
{{ "/testdb" | parentPath }} {# → "/" #}
{{ "/" | parentPath }} {# → "/" (root preserved) #}
Common pattern (Back link on document detail page):
<a href="{{ path | stripTrailingSlash | parentPath }}" role="button">
← Back to {{ coll }}
</a>
toJson
Serializes objects to JSON strings with optional pretty printing (pretty, default true). A null input yields null. The output is HTML-escaped like any other expression: add | raw where the JSON must stay unescaped, e.g. inside <script>.
{{ item.data | toJson }} {# pretty-printed, default #}
{{ roles | toJson(pretty=false) }} {# compact #}
Common patterns:
<!-- Pass the tenant id to JavaScript ("acme" or null) -->
<script>
const tenantId = {{ tenantId | toJson | raw }};
</script>
<!-- Pass document data to JavaScript -->
<script>
const productData = {{ item.data | toJson | raw }};
</script>
Filter Chaining
<!-- Navigate to parent collection -->
<a href="{{ path | stripTrailingSlash | parentPath }}">Up</a>
<!-- Build URL with cleaned base path -->
{% set cleanPath = path | stripTrailingSlash %}
<a href="{{ cleanPath | buildPath(item.value) }}">{{ item.value }}</a>
See Also
- Developer's Guide — Complete guide with filter usage examples
- Pebble Template Documentation — Template syntax reference
- RESTHeart Documentation — RESTHeart API reference