Skip to content

This page is for integrators and developers who export records with a template through the API, read or write template definitions, or need to know exactly how a template is rendered.

OSOS has two distinct template concepts, both stored inside the DataEntity document (not as standalone collections):

  1. Export templates — uploaded Word/HTML/Excel files that OSOS fills with entry data to produce DOCX, PDF, or XLSX documents. These drive the entries/export/{templateId} endpoint.
  2. Display templates and template parameters — a templateId plus a set of parameterized bindings (TemplateParameter) attached to an entity or a view, used to parameterize how an entry or list is rendered.

The supported outputs are DOCX, HTML, and XLSX, with DOCX/HTML → PDF conversion. Template exports never produce CSV: CSV is offered only by the two quick exports of a gallery or of an entity’s entries (format=xlsx|csv, Since 1.10; see Quick export of an entity’s entries). Template values are filled with tokens/expressions resolved against the entry at export time, and JavaScript plus custom functions can be used inside the template.

Reports are not rendered by this engine. An earlier version of the builder page listed Reports among the places templates are used, “rendering through the same engine”. In the code, a report renders through ReportService → ExportService (data-service/src/services/report.service.ts), not through DataEntryTemplateExportService; see Reports.

Sensitive fields in a template export Since 1.10

Section titled “Sensitive fields in a template export Since 1.10”

A template carries its own sensitiveDataAccessPolicy (Prohibited, Privileged, User-Based, Auto; absent = Privileged). The template read disables the caller-scoped mask (disabledStages.hideSensitiveFields: true) and, when the template’s policy resolves to anything short of a full reveal, passes elementSensitiveAccess with the resolved grant scopes instead. The template’s own policy applies even when a reaction’s Generate File action renders it (a reaction’s policy does not override it). An unknown executor makes a User-Based or Auto template mask (fail closed). Encrypted fields are masked unconditionally by maskFieldsExcludedFromBuilders before any expression is evaluated or anything is rendered. See Sensitive-data access policy.

The authoring syntax for HTML (EJS), Word and Excel templates, with examples, is in Export templates — Write the template file.

Export template (DataEntityExportTemplate)

Section titled “Export template (DataEntityExportTemplate)”

Export templates are stored on DataEntity.templates (IDataEntityExportTemplate[]). Each template references an uploaded source file and declares how it should be rendered and delivered.

FieldTypeRequiredMeaning
idUUIDyesTemplate identifier (used as templateId in the export endpoint)
nameLocalizedValueyesLocalized template name; also the default output file name
levelTemplateLevelEnumyesSingleEntry (0) or MultipleEntries (1)
typeTemplateTypeEnumyesOutput format: Word (0), PDF (1), Excel (2)
fileFileModelyesThe uploaded source template file (has id, mimeType, name)
exportTypeTemplateExportTypeEnumyesUI (0) = synchronous download, Background (1) = async via service bus
additionalPropertiesRecord<string,string>noCustom variables (expressions) and feature flags such as extended
queryreference or nullnoSince 1.10. Saved query an entry must meet (Single Entry only) — see Conditional export
criteriaFilterExpressionnoSince 1.10. Filter an entry must meet (Single Entry only)
nonMatchEntriesModeenumnoSince 1.10. Disable (0, default) or Hidden (1) for entries that do not meet the condition
sensitiveDataAccessPolicySensitiveDataAccessPolicyEnumnoSince 1.10. What the template may disclose from sensitive fields; absent = Privileged. See Sensitive fields in a template export

Notes verified from code:

  • type (the requested output format) is independent of the source file’s MIME type. For type === PDF, the service branches on file.mimeType: a DOCX source is rendered then converted DOCX→PDF; an HTML source is rendered then converted HTML→PDF. Any other source MIME type for a PDF template yields no file.
  • level controls per-entry helpers: getEntryComments and getEntryEmails return [] unless level === SingleEntry (see Custom functions).

The output format determines which templating engine runs:

typeSource fileEngineDelimiters
WordDOCXdocx-templates createReport{{ … }} (cmdDelimiter), fixSmartQuotes: true
PDF (from DOCX)DOCXdocx-templates, then DOCX→PDF conversion{{ … }}
PDF (from HTML)HTMLejs.render (async), then HTML→PDF conversionopenDelimiter: '{{', closeDelimiter: '}}'
ExcelXLSXxlsx-template (substitute(1, data)); a streamable template is written by ExcelJS’s streaming writer instead (Since 1.4, see Large exports)library default (${...} placeholders)

The data object passed to every engine is { entries, entity } (plus extra collections for extended export — see below). For Excel, entries are first flattened by mapEntriesForExcelTemplate: resolved reference arrays are collapsed to comma-joined mainTitle strings per available language, and vertical-tab characters are replaced with spaces.

Since 1.4.

Display/parameterized templates use TemplateParameter, defined in models/template-parameter.model.ts and @osos/shared.

FieldTypeRequiredMeaning
namestringyesParameter name; must match the parameter name in the template
valueTypeTemplateParameterValueTypeEnumyesFixed (0), Expression (1), Field (2)
valueanynoFixed value, or an entry expression such as value.my_block[scope.index].my_field when Expression
componentstringnoOptional component reference
sourcestringnoOptional source reference

valueType semantics from the model JSDoc: Fixed — value is used verbatim; Expression — value is an entry expression evaluated to produce the value; Field — value type 2 (the enum member exists; its resolution is performed by consumers, see Notes and uncertainties).

Parameters are grouped by render context in TemplateParameterTypes:

interface TemplateParameterTypes {
listEntry?: TemplateParameter[]; // list rendering
viewEntry?: TemplateParameter[]; // read/view rendering
editEntry?: TemplateParameter[]; // edit rendering
}

This bundle is attached in two places, both { templateId, parameters }:

  • DataEntity.displayTemplate → EntityDisplayTemplate
  • A data view → ViewDisplayTemplate
GET /v1/entities/{entity}/entries/export/{templateId}

Controller: DataEntryTemplateExportController.exportEntriesWithTemplateV2. Authenticated (Auth2 strategy). Produces a file download (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, ...wordprocessingml.document, or application/pdf) or a JSON acknowledgement.

Path parameters:

NameInMeaning
entitypathData entity id
templateIdpathExport template id (the id on DataEntity.templates[*])

Query parameters:

NameTypeMeaning
modenumber (ExportWithTemplateSourceMode)SelectedItems (0) or source (1)
itemsToExportstring[]Entry ids to export; required when mode === SelectedItems
filterCriteriaobjectFilter criteria applied when mode === source
searchstringFree-text search (ignored/forced undefined in SelectedItems mode)
sourceCollectionstringCollection id; its items are added as an _id IN (...) filter in source mode
appliedQuickFiltersstring[]Quick-filter ids

Behavior (verified):

  1. Loads the entity, then getEntityTemplate(dataEntity, templateId) — throws TemplateNotExists (HTTP 404, code TEMPLATE_NOT_EXIST) if no template with that id exists on the entity.
  2. Extended templates — if additionalProperties.extended === 'true', delegates to DataEntryExtendedTemplateExportService.exportFromTemplate (see Extended export). Always synchronous.
  3. Background export — else if exportType === Background, sends an ExportTemplateInBackgroundCommand on the service bus and immediately returns 200 { "success": true }. The file is generated asynchronously by ExportTemplateInBackgroundHandler and delivered via a FileGeneratedEvent.
  4. UI export — else renders synchronously via exportEntriesWithTemplate, uploads the result to storage, publishes FileGeneratedEvent, sets Content-Type/attachment headers, and streams the file body back.

In cases 2 and 4 the generated file is also uploaded to the storage service and a FileGeneratedEvent is published (carrying the file, template id, exportType, entity id, and the list of exported entry ids).

Error cases:

ConditionExceptionHTTP
No template with templateId on the entityTemplateNotExists404
mode === SelectedItems with empty/missing itemsToExportMustProvideITemsToExportProperty400
The entry does not meet the template’s condition, or a conditioned template is called in source mode (Since 1.10)TEMPLATE_CONDITIONS_NOT_MET422
GET /v1/templates/{id}/used

Controller: TemplatesController.isTemplateUsed. Returns a boolean. Long-standing.

This operates on templates stored as data entries in the internal templates entity (StringConstants.TEMPLATES_ENTITY_NAME = 'templates'), i.e. message/email templates referenced by entity triggers — not on the DataEntityExportTemplate export templates above.

Logic (verified):

  1. Look up the template entry by id; return false if it does not exist.
  2. If the template’s value.template_type.id === 'EMAIL_PART_TEMPLATE', find the main templates that reference this part as their header or footer (value.template_details.template_header.dataEntry / template_footer.dataEntry equal to id); collect those ids. Otherwise the candidate set is just this template’s own id.
  3. Return true if any DataEntity has a trigger action wired to one of those template ids (triggers.actions.options.template IN (...)); otherwise false.

exportEntriesWithTemplate is the core renderer used by the UI export path, the background handler, and the internal GenerateFileFromTemplateHandler. Steps:

  1. Fetch the source file from storage as an arraybuffer.
  2. Resolve the output file name — the passed selectedFileName, else the localized template name.
  3. Gather export data (getTemplateExportData):
    • mode === source: builds filters from the source collection’s items (_id IN) and any filterCriteria.criteria.
    • mode === SelectedItems: requires itemsToExport, forces search = undefined, and filters _id IN itemsToExport.
    • A view-triggered export reads through the view’s own columns. The view’s configured fields are its display columns, and buildScope uses the same list both to narrow which relation/ADT fields it resolves and to build the read’s $project, so a template referencing a field the triggering view does not display renders that field blank (known limitation, still open). An earlier version of this page said the export widened to every non-sensitive field Since 1.8; that widening was reverted, because a $project naming both a block and its sub-field (value.address and value.address.street) is a MongoDB path collision that produced a file with no records at all (data-entry-template-export.service.ts, getTemplateExportData JSDoc). The view’s row-level scoping (obsolete/invalid/archived and search rules, its query data source, its default sorting) still applies.
    • Runs dataEntryService.findWithResolvesFactory with disabledStages.hideSensitiveFields: true — this disables the caller-scoped mask, so the template’s own sensitive-data access policy decides (elementSensitiveAccess); Encrypted fields are then masked unconditionally.
    • If the template declares additionalProperties, evaluates them per entry (see Custom variables).
  4. Render with the engine matching type (see the table above), injecting the shared custom functions.
  5. Return { fileName, fileContent, mimeType, exportEntriesIds }.

Long-standing.

additionalProperties is a Record<string, string> where each value is an expression wrapped in {{%= … %}}. During data gathering, parseAdditionalProperties strips the {{%= / %}} wrappers, evaluates the inner expression per entry via executeExpression, and merges the results into each entry.value under the property key — making them available to the template as normal fields.

executeExpression builds a JS Function whose scope is { ...sharedCustomFunctions, entry, dataEntity }, evaluates return <expression>;, and awaits the result if it is a function call and/or Promise. Because expressions are evaluated as raw JavaScript, they run with full access to the shared function set below.

The reserved key extended (additionalProperties.extended === 'true') is a feature flag, not a variable — it routes the export to the extended service.

Every render (docx, html/ejs, and expression evaluation) receives a shared function set from getSharedCustomFunctions(entity, templateConfig). Verified functions:

FunctionPurpose
today(manipulateAmount?)Current date, timezone-adjusted, with optional date-math manipulation
date(value, formatString?, tzOffset?)Format a date (default Constants.DATE_FORMAT), timezone-adjusted
loc(localizedValue)Resolve a LocalizedValue to the user’s language
formula(text)Excel only: the one way to emit a formula cell (a plain string starting with = stays text)
mdToText(value)Strip Markdown to plain text (also normalizes single-tilde strikethrough and line breaks)
fetchEntry(ref)Resolve a single referenced entry from { dataEntity, dataEntry }
fetchEntriesById(entityId, entriesIds)Resolve multiple entries by id
fetchEntries(entityId, filter)Resolve entries by an arbitrary filter
getStepName(entry, stepId)Workflow step name (falls back to ad-hoc steps)
getCurrentStepOwner(entry)Owner of the active current step (if it has a resolved mainTitle)
getStepOwner(entry, stepId)Owner of a step from workflow history
getStepReceivedAt(entry, stepId?)Received-at timestamp for a step (handles recievedAt/receivedAt)
getStepActions(entry, stepId)Actions defined on a step
getStepActionName(entry, stepId, actionId)Name of a specific step action
getStepHistory(entry, stepId)All history records for a step in the active workflow
getStepLastHistory(entry, stepId)Most recent history record for a step
getEntryComments(entry, lang?)Entry comments (with mentions resolved); [] unless level === SingleEntry
getEntryEmails(entry)Emails associated with the entry; [] unless level === SingleEntry

DOCX and HTML renders additionally get:

  • DOCX — getImage(image, width, height, entryId?, alt?) returns image bytes for embedding (supported extensions: png, gif, jpg, jpeg, svg; unsupported extensions are logged and skipped) and mdToHtml(value) renders Markdown to HTML wrapped in <body>…</body> (with single- and double-tilde strikethrough support).
  • HTML/EJS — getImageSrc(image, entryId?) returns a base64 data: URI for the image, and mdToHtml(value) (configured with breaks: true).

When exportType === Background, the endpoint enqueues an ExportTemplateInBackgroundCommand (carrying the entity id, the full entityTemplate, mode, itemsToExport, sourceCollection, filterCriteria, search, view, and appliedQuickFilters) with sticky attributes for user, space, and delegation, then returns { success: true }.

ExportTemplateInBackgroundHandler re-loads the entity, calls the same exportEntriesWithTemplate, uploads the result, and publishes a FileGeneratedEvent (with exportType = Background) plus a CommandExecutedMessage over the socket. Errors are logged and swallowed (no failure event is published on error in this handler).

GenerateFileFromTemplateHandler handles GenerateFileFromTemplateCommand (used by workflow/automation actions, not an HTTP route). It optionally loads a view by viewId, resolves the entity and template, calls exportEntriesWithTemplate with command.fileName, optionally uploads to storage when uploadToStorageService is set, and returns the file (or the uploaded file record) in a CommandExecutedMessage. On error it emits a CommandExecutedMessage with success: false and the error.

Since 1.6.

DataEntryExtendedTemplateExportService.exportFromTemplate is used when additionalProperties.extended === 'true'. It runs the same gather-and-render pipeline but always in source mode and enriches the template data object with entity-model context beyond { entries, entity }:

{ entries, entity, module, reactions, notifications, workflows,
lists, queries, views, relations }

These are resolved from the data entity (getModule, getReactions, getNotifications, getWorkflows, getLists, getQueries, getViews, getRelations), making it suitable for generating documentation/specification exports of an entity’s configuration itself. It shares the same engine selection and custom-function set as the base service. This path is always synchronous (no background branch).

An Excel template export of many entries is written page by page (500 entries at a time, each page written and released before the next is read) when the template has a simple enough shape; any other shape is rendered in memory as before. The difference matters at scale: in the measurement that came with the change, 25,000 entries took 12.8 s instead of 323 s, with about a quarter of the memory, and the file was 3 MB instead of 24 MB. This was also delivered to the 1.4, 1.6 and 1.8 lines as an update.

A template is streamed only when all of these hold:

  • It has exactly one sheet.
  • Every placeholder fills a whole cell, is a plain ${table:entries.<key>} (no sub-type), and all of them sit on the same row; that row holds nothing else.
  • Nothing below that row has a value, and no merged range reaches the table row or below it.
  • The sheet has no formulas, images, Excel tables, conditional formatting, data validation, auto-filter or defined names.

When a template does not qualify, data-service logs the reason at INFO (template <id> of entity <id> is rendered in memory: it …), which tells you what to remove. Operators can force every template back to in-memory rendering with TEMPLATE_EXPORT_XLSX_STREAMING_DISABLED=true. On both paths a user value that starts with = stays text; only a value produced by the formula() expression helper is written as a formula.

The Templates tab is also available on virtual entities such as Groups: templates can be managed on a virtual entity when it is not implicit, or when it is implicit but allows editing (implicitOptions.allowEdit); otherwise the entity’s normal edit rule applies. A template on a proxy, joiner or aggregate virtual entity is saved through the virtual-entity endpoint (PUT /v1/entities/virtual/{id}). A template export over a virtual entity includes the rows the user selected. Both were also delivered to the 1.6 and 1.8 lines as an update (the selected-rows fix also to the 1.4 line). For the other admin operations on virtual entities, see Virtual entities: admin operations.

A Single Entry export template can carry a condition, so that only entries that meet it can be exported with that template. In the template form, the Filter section sets the condition and For other entries decides what users see on an entry that does not meet it: Disable export option (the default) or Hide export option. A Multiple Entries template cannot have a condition (its filter controls are disabled). A template without a condition behaves exactly as before.

The condition is stored on the template:

PropertyMeaning
queryA saved query the entry must meet (null clears it).
criteriaA filter expression the entry must meet.
nonMatchEntriesModeDisable (0, the default when absent) or Hidden (1) — the same values system buttons use.

A template “has a condition” when it is Single Entry and has a saved query or at least one criteria rule; an empty rule group is not a condition. A saved query that cannot be loaded, or criteria that cannot be parsed, matches no entry (and is logged).

  • Status route. POST /v1/entities/{entity}/templates/status/entries with {dataEntriesIds: string[]} (1 to 100 ids) returns [{templateId, isDisabled, isHidden}] for each conditioned template. Through a view it reports only the templates that view exposes, and evaluates conditions only when the view can read every requested entry; outside a view it is open to system viewers and above, like the export route. Row and entry-details menus use it to show each template enabled, disabled (with the reason on hover) or hidden, and call it only when a presented template has a condition. Views that expose a template have the route in their execution plan (migration 1.10.0-a22 backfilled existing views).
  • Export route. GET /v1/entities/{entity}/entries/export/{templateId} refuses an entry that does not match, and any mode other than selected items for a conditioned template, with 422 TEMPLATE_CONDITIONS_NOT_MET. The check runs before anything is rendered or queued.
  • Not gated. The Generate File From Template reaction action does not apply template conditions.
FeatureSinceEvidence
Template parameters + display template models (TemplateParameter, EntityDisplayTemplate, ViewDisplayTemplate)1.4introduced in 1.4.0-alpha.01
Extended template export (exportFromTemplate / extended flag)1.6first tag 1.6.0
Background export (TemplateExportTypeEnum, ExportTemplateInBackgroundCommand, FileGeneratedEvent)Long-standingpre-1.2
Custom variables (additionalProperties / parseAdditionalProperties)Long-standingpre-1.2
GET /v1/templates/{id}/usedLong-standingpre-1.2
Streamed Excel template exports (500 entries per page)1.4first published on the 1.4 line; also delivered to the 1.6 and 1.8 lines
Selected virtual rows included in a template export1.4delivered to the 1.4, 1.6 and 1.8 lines
Templates tab on virtual entities1.6frontend, 1.6 and 1.8 lines
Conditional export (query / criteria / nonMatchEntriesMode, status route, TEMPLATE_CONDITIONS_NOT_MET)1.10develop only (migration 1.10.0-a22)
Per-template sensitive-data access policy (sensitiveDataAccessPolicy)1.10form control shown only when the entity has a sensitive field
  • TemplateParameterValueTypeEnum.Field (value 2) exists in the model and enum, but the primary sources do not contain the code that resolves a Field parameter into a runtime value; resolution appears to happen in a consumer not covered by the cited sources (likely the frontend or another service). The Fixed/Expression semantics are documented in the model JSDoc; Field semantics are inferred from the enum name only.
  • The internal templates entity used by GET /v1/templates/{id}/used (with template_type, template_details.template_header/footer, EMAIL_PART_TEMPLATE) is a data-entry-shaped structure whose full schema is not defined in the cited source files; field paths were read directly from the controller query.
  • Features marked Long-standing first shipped in pre-1.2 release tags; 1.2 is the earliest milestone in the tracked scheme, so the exact milestone of first availability is not distinguishable.
  • The Excel path uses xlsx-template’s default placeholder syntax; the exact delimiter is defined by that library, not by OSOS code, so it is described generically here.

Platform 1.10.0 · Backend 1.11.0-alpha.11 · Frontend 1.11.0-alpha.6 · Mobile 1.10.2 · Chart 1.11.8 · Gateway 2.6.11 · MCP 0.2.0 · Grafana DS 1.2.0Docs build 2026-11-27